发布网友 发布时间:2022-04-23 03:03
共1个回答
热心网友 时间:2023-07-17 04:29
没写4个类,直接new的,效果一样.
import java.util.concurrent.LinkedBlockingQueue;
public class SequentialOutputDemo {
public static void main(String[] args) {
final LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(8);
queue.offer(0);
queue.offer(1);
queue.offer(2);
queue.offer(3);
//控制调用次数
final int count = 3;
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while(i<count){
/**
* 检测队首的元素是否为当前线程需要
*/
int index = queue.peek();
if(index == 0){
System.out.print("1");
/**
* 取出队首的令牌并保证原子性插入队尾
*/
pollAndOffer(queue);
i++;
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while(i<count){
int index = queue.peek();
if(index == 1){
System.out.print("2");
pollAndOffer(queue);
i++;
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while(i<count){
int index = queue.peek();
if(index == 2){
System.out.print("3");
pollAndOffer(queue);
i++;
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while(i<count){
int index = queue.peek();
if(index == 3){
System.out.print("4");
pollAndOffer(queue);
i++;
}
}
}
}).start();
}
private static void pollAndOffer(LinkedBlockingQueue<Integer> queue){
synchronized (queue) {
queue.offer(queue.poll());
}
}
}
这输出的是123412341234,
想输出的214321432143的话,把
queue.offer(0); ┐ │ queue.offer(1);
queue.offer(1); │ │ queue.offer(0);
│ 换成 ------>│
queue.offer(2); │ │queue.offer(3);
queue.offer(3); ┘ │ queue.offer(2);
同理 432143214321 的话:
queue.offer(3); queue.offer(2); queue.offer(1); queue.offer(0);