转自https://blog.csdn.net/weixin_49920327/article/details/123561378
1. 继承Thread类
1)创建一个类,继承 Thread并重写 run 方法
2)创建对象 执行 start 方法
//创建线程方式一:继承Thread类,重写run()方法,调用start()开启线程
public class TestThread1 extends Thread{
@Override
public void run() {
//run()方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码——————" +i);
}
}
public static void main(String[] args) {
//main()线程,主线程
//创建一个对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程" + i);
}
}
}
2. 实现Runnable接口
1)创建一个类 实现Runnable接口并实现 run 方法
2)创建一个 该类 对象
3)创建一个 Thread 对象,构造方法入参为 该类 对象
4)Thread 对象 执行start方法
//创建线程方式2:实现runnable接口,重写run方法,执行线程丢入runnable接口实现类,调用start()方法
public class TestThread3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("线程" + i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
//创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread(testThread3);
// thread.start();
new Thread(testThread3).start();
for (int i = 0; i < 20; i++) {
System.out.println("学习" +i);
}
}
}
3. 实现Callable接口(了解)
1)创建一个类实现 Callable 接口 ,重写 call 方法
2) 创建目标对象
3) 创建一个执行服务
4)提交执行
5)获取返回结果
6)关闭执行服务
//实现一个类,重写call()方法,
public class TestCallable implements Callable<Boolean> {
@Override
public Boolean call() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + "在上班-----" + i);
}
return Boolean.TRUE;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable();
TestCallable t2 = new TestCallable();
TestCallable t3 = new TestCallable();
//创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> result1 = executorService.submit(t1);
Future<Boolean> result2 = executorService.submit(t2);
Future<Boolean> result3 = executorService.submit(t3);
//获取结果
Boolean r1 = result1.get();
Boolean r2 = result2.get();
Boolean r3 = result3.get();
//关闭服务
executorService.shutdownNow();
}
}