1.实现Runnable
2.继承Thread
3.实现Callable, 用FutureTask
public static void main(String args[]) throws Exception {
// 1 使用lamda
FutureTask<Integer> future = new FutureTask<>(
() -> {
System.out.println("work");
for (int i = 1; i <= 5; i++) {
System.out.println("working");
Thread.sleep(1000);
}
System.out.println("done");
return 5;
}
);
// 2 直接用类
SubThread subThread = new SubThread();
FutureTask<Integer> future1 = new FutureTask<>(subThread);
new Thread(future, "有返回值").start();
while (!future.isDone()) {
System.out.println("哈哈数钱中……");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(future.get());
}
static class SubThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("work");
for (int i = 1; i <= 5; i++) {
System.out.println("working");
Thread.sleep(1000);
}
System.out.println("done");
return 5;
}
}
4.使用线程池