需求:3個線程 輸出ABC ------> ABCABCABC。。。。。此類型
1、 使用線程池 将所有線程放入一個隊列 ,保證順序輸出
public class ThreeThread {
public static void main(String[] args) throws InterruptedException {
//用線程池來實作 ,3個線程加入線程池
ExecutorService pool = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
pool.submit(()-> System.out.println("AAAAAA"));
pool.submit(()-> System.out.println("BBBBBB"));
pool.submit(()-> System.out.println("CCCCCC"));
}
pool.shutdown();
}
}
2、使用 wait(), synchronized(同步鎖) 輪詢機制 到誰了 誰輸出
public class ThreeThread {
public static void main(String[] args) throws InterruptedException {
Param param = new Param();//A開始列印
new Thread(new Letter(param, "A", 0)).start();
new Thread(new Letter(param, "B", 1)).start();
new Thread(new Letter(param, "C", 2)).start();
}
}
class Letter implements Runnable {
private Param param;
private String name;
private int process;
Letter(Param param, String name, int process) {
this.param = param;
this.name = name;
this.process = process;
}
@Override
public void run() {
synchronized (param) {
for (int i = 0; i < 10; i++) {
int state = param.getState();
while (state != process) {
try {
param.wait();//進入阻塞狀态,釋放該param對象 鎖
} catch (InterruptedException e) {
e.printStackTrace();
}
state = param.getState();//再一次的擷取最新的狀态
}
System.out.println("----- " + name + " -----");
param.setState(++state % 3);//設定狀态
param.notifyAll();//釋放其他的2個阻塞狀态
}
}
}
}
// 為了同步取值
class Param {
//狀态 0 -> A 啟動
private int state = 0;
public int getState() { return this.state; }
public void setState(int state) { this.state = state; }
}