没写4个类,直接new的,效果一样.
import java.util.concurrent.LinkedBlockingQueue;
public class SequentialOutputDemo {
public static void main(String[] args) {
final LinkedBlockingQueue
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
* 检测队首的元素是否为当前线程需要
*/
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
if(index == 1){
System.out.print("2");
pollAndOffer(queue);
i++;
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while(i
if(index == 2){
System.out.print("3");
pollAndOffer(queue);
i++;
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while(i
if(index == 3){
System.out.print("4");
pollAndOffer(queue);
i++;
}
}
}
}).start();
}
private static void pollAndOffer(LinkedBlockingQueue
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);