一、创建无返回值的线程
(1)继承Thread类,重写 run() 方法
- 定义类继承Thread类
- 重写Thread类的 run() 方法;(目的:将自定义的代码存放在 run 方法中,让线程来执行)
- 调用线程的 start() 方法:该方法有两步:启动线程,调用 run() 方法
public class Test{
static class MyTask extends Thread{
@Override
public void run() {
System.out.println(2);
}
}
public static void main(String[] args) {
System.out.println(1);
new MyTask().start();
System.out.println(3);
try{
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(4);
}
}
结果为:1 3 2 4
(2)创建类实现Runable 接口
- 创建任务:创建类实现Runable 接口
- 使用Thread 为这个任务分配线程
- 调用线程的start() 方法
public class Test{
public static void main(String[] args) {
System.out.println(1);
// 注意,这里new的是Thread
new Thread(new Task()).start();
System.out.println(3);
try {
// 睡眠的是主线程
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(4);
}
static class Task implements Runnable {
public void run() {
System.out.println(2);
}
}
}
结果为:1 3 2 4
(3)使用Lammbda 表达式
public class Test{
public static void main(String[] args) {
System.out.println(1);
new Thread(()-> System.out.println(2)).start();
System.out.println(3);
try {
// 睡眠的是主线程
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(4);
}
}
结果为:1 3 2 4
二、创建有返回值的线程
需要先实现Callable<T>接口并重写其 call() 方法,然后new一个FutureTask<T>用于存放返回值,将类传入FutureTask中,再将FutureTask传入Thread中去调用start()方法,即可执行call() 中的代码
public class Test implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return 2;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(1);
// 保存一个将来的返回值
FutureTask<Integer> future = new FutureTask<Integer>(new Test());
new Thread(future).start();
System.out.println(3);
// 主线程阻塞,等待Thread线程的返回值
Integer integer = future.get();
System.out.println(integer);
System.out.println(4);
}
}
结果为:1 3 2 4