前言
public class ThreadTest02 {
public static void main(String[] args) throws InterruptedException {
SynchronousQueue<Integer> one2two = new SynchronousQueue<>();
SynchronousQueue<Integer> two2three = new SynchronousQueue<>();
SynchronousQueue<Integer> three2one = new SynchronousQueue<>();
new Thread(new PrintTask(three2one, one2two)).start();
new Thread(new PrintTask(one2two, two2three)).start();
new Thread(new PrintTask(two2three, three2one)).start();
three2one.put(1);
}
}
class PrintTask implements Runnable {
private SynchronousQueue<Integer> in;
private SynchronousQueue<Integer> out;
public PrintTask(SynchronousQueue<Integer> in, SynchronousQueue<Integer> out) {
this.in = in;
this.out = out;
}
@Override
public void run() {
try {
long id = Thread.currentThread().getId();
int data = 0;
while (true) {
data = in.take();
System.out.println("当前线程:" + id + "打印数字为:" + data);
if (data + 1 <= 100)
out.put(data + 1);
if (data + 3 > 100)
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}