1 继承Thread类:本质实现了Runnable接口,调用start()方法开启新线程,并执行run()方法。
2 实现Runnable接口
3 使用Callable接口创建线程返回值
执行 Callable 任务后,可以获取一个 Future 的对象,在该对象上调用 get 就可以获取到 Callable 任务返回的 Object 了,再结合线程池接口 ExecutorService 就可以实现传说中有返回结果的多线程了。
public class TestCallable {
public static void main(String[] args) {
Thread1Demo td = new Thread1Demo();
//1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask task = new FutureTask<>(td);
new Thread(task).start();
try {//2.接收线程运算后的结果
if (!task.isDone()) {
System.out.println(“task has not finished, please wait!”);
}
Integer sum = task.get(); //FutureTask 可用于 闭锁
System.out.println(“task return: -----” + sum);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
class Thread1Demo implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100000; i++) { sum += i; }
return sum;
}
}
4 基于线程池的方式有返回值
不用每次都创建线程,使用Executor创建线程池,向其中加入任务。
public class ThreadPoolDemo {
public static void main(String[] args) {
//创建线程池
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
//向线程池提交任务
Future future = newCachedThreadPool.submit(new MyCallable());
if (!future.isDone()) {
System.out.println(“task has not finished, please wait!”);
}
try {
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
} finally {
newCachedThreadPool.shutdown();
}
}
}
class MyCallable implements Callable {
@Override
public String call() throws Exception {
String value = “test”;
Thread.currentThread().sleep(5000);
return value;
}
}