Java创建线程的方式
创建线程的方法
1. 直接使用Thread
public class Test1 {
public static void main(String[] args) {
// 1.创建线程
Thread t = new Thread() {
// 2. 线程要执行的任务
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " running...");
}
};
t.start();
System.out.println(Thread.currentThread().getName() + " running...");
}
}
2. 使用Runnable配合Thread
线程和任务分离开来
public class Test2 {
public static void main(String[] args) {
// 线程要执行的任务
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " running...");
}
};
// 2. 创建线程
new Thread(runnable).start();
System.out.println(Thread.currentThread().getName() + " running...");
}
}
Runnable的创建也可以使用lambda表达式来处理:
@Test
public void test2() {
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getName() + " running...");
};
}
3. 使用FutureTask、Callable、Thread组合获取线程返回值
public class Test3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return 100;
}
});
Thread t = new Thread(futureTask, "futureTask thread");
t.start();
System.out.println(futureTask.get());
}
}