方法1:继承Thread类
- 子类继承:Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
public class TestThread1 extends Thread{
@Override
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("sub"+i);
}
}
public static void main(String[] args) {
TestThread1 testThread01 = new TestThread1();
testThread01.run();
for (int i = 0; i < 20; i++) {
System.out.println("main" + i);
}
}
}
方法2:实现 Runnable接口
- 实现接口 Runnable 具有多线程能力
- 启动线程:传入目标对象 + Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
public class TestThread3 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("sub" + i);
}
}
public static void main(String[] args) {
TestThread3 testThread3 = new TestThread3();
new Thread(testThread3).start();
for (int i = 0; i < 20; i++) {
System.out.println("main" + i);
}
}
}
方法3:实现 Callable接口
- 实现 callable接口,需要返回值类型
- 重写call()方法,需要抛出异常
- 创建目标对象
- 创建执行服务: ExecutorService ser= Executors.newFixedThreadPool(1)
- 提交执行: Future<Boolean> result1= ser.submit(t1)
- 获取结果: boolean r1= result1.get()
- 关闭服务: ser.shutdownNow();