创建线程的三种方式
- 继承Thread类,重写run()方法
- 实现Runnable接口
- 实现Callable接口
第一种继承Thread类
- 继承Thread类
- 重写run方法
- 创建线程类
- start()执行
public class TestCreateThread {
public static void main(String[] args) {
// 第三步
MyThread myThread = new MyThread();
// 第四步
myThread.start();
}
}
// 第一步
class MyThread extends Thread{
// 第二步
@Override
public void run() {
System.out.println("我被执行了");
}
}
第二种实现Runable接口
- 实现Runnable接口
- 重写run()方法
- 创建实现Runnable接口的对象
- 通过3创建Thread对象
- 执行start()方法
public class TestThread {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt).start();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println("多线程");
}
}
第三种实现Callable接口
- 实现Callable接口,需要返回值
- 重写call()方法,需要返回值一致
- 创建实现Callable接口的对象
- 创建服务(线程池)
- 执行
- 获取结果
- 关闭服务
public class TestThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThread mt = new MyThread();
// 创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 执行
Future<Boolean> submit = executorService.submit(mt);
// 获取结果
Boolean aBoolean = submit.get();
System.out.println(aBoolean);
// 关闭服务
executorService.shutdownNow();
}
}
class MyThread implements Callable<Boolean>{
@Override
public Boolean call() {
System.out.println("多线程");
return true;
}
}