创建线程的三种方式
1. Thread
匿名内部类
@Slf4j
public class CreateThread {
public static void main(String[] args) {
Thread t1 = new Thread("t1") {
@Override
public void run() {
log.info("hello world");
}
};
t1.start();
}
}
2.定义 Runable
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
log.debug("runnable");
}
};
Thread t2 = new Thread(runnable, "t2");
t2.start();
}
可简写为:
public static void main(String[] args) {
Runnable runnable = () -> log.info("runnable");
Thread t2 = new Thread(runnable, "t2");
t2.start();
}
3.FutureTask
获取返回参数
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
log.info("futuretask");
return 1;
}
});
Thread t3 = new Thread(task, "t3");
t3.start();
log.info("{}",task.get());
}
可简写为:
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> task = new FutureTask<>(() -> {
log.info("futuretask");
return 1;
});
Thread t3 = new Thread(task, "t3");
t3.start();
log.info("{}",task.get());
}