1.JOIN
package com.gupao.forkjoin;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 功能:
*
* @author kangping
* @date 2022-07-05 6:56 下午
*/
public class Main {
public static void main(String[] args) {
final Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + " run 1");
}
}, "T1");
final Thread t2 = new Thread(new Runnable() {
public void run() {
try {
// t2 线程阻塞 等待t1线程执行完
t1.join(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " run 2");
}
}, "T2");
final Thread t3 = new Thread(new Runnable() {
public void run() {
try {
// t3 线程阻塞 等待t2线程执行完
t2.join(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " run 3");
}
}, "T3");
t1.start();
t2.start();
t3.start();
}
}
2.线程池
newSingleThreadExecutor 里面只有1个线程,依次执行run方法
package com.gupao.forkjoin;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 功能:
*
* @author kangping
* @date 2022-07-05 6:56 下午
*/
public class Main {
public static void main(String[] args) {
final Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + " run 1");
}
}, "T1");
final Thread t2 = new Thread(new Runnable() {
public void run() {
try {
t1.join(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " run 2");
}
}, "T2");
final Thread t3 = new Thread(new Runnable() {
public void run() {
try {
t2.join(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " run 3");
}
}, "T3");
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(t1);
executorService.submit(t2);
executorService.submit(t3);
}
}