需求: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; }
}