class SampleThread extends Thread {
//重写run方法,线程运行后,跑的就是run方法
public void run(){
//System.out.println("");
}
public static void main(String[] args){
Thread t1 = new SampleThread();
Thread t2 = new SampleThread();
t1.start(); //线程运行,调用的 run()方法.
t2.start(); //线程运行,调用的 run()方法..
}
}
class A implements Runnable{
@Override
public void run() {
// implement run method here
}
public static void main() {
final A obj = new A();
Thread t1 = new Thread(new A());
t1.start();
}
}
class MyCallable implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) throws Exception {
MyCallable mc = new MyCallable(); //实例化 callable
FutureTask oneTask = new FutureTask(mc); //用FutureTask包裹
Thread oneThread = new Thread(oneTask); //用Thread包裹
oneThread.start();
System.out.print(oneTask.get()); //获取返回值
}
}
Callable 方法在 Java 8 后,支持拉姆达表达式的写法,可以创建一个 FutureTask 类,语句上不是太罗嗦。
Callable 方式有以下几个优点:
下面代码演示了使用 FutureTask 类运行线程,捕获异常的例子:
FutureTask<Integer> task=new FutureTask<Integer>(()->{
throw new Exception("自定义异常");
});
new Thread(task).start();
try {
System.out.println(task.get());
} catch (Exception e) {
System.out.println(e.getMessage());
}
Java 6 之后,还可以通过创建线程池来创建线程,使用 ExecutorService 的 execute 方法:
ExecutorService es = Executors.newCachedThreadPool();
Runnable r = <your runnable here>;
es.execute(r);
原创文章,转载请注明出处!https://cloud.tencent.com/developer/article/1362835