直接上代碼
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by chenzhichao on 16/11/2.
*/
public class TestQueue {
private static ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
private static AtomicInteger index = new AtomicInteger(0);
private static int[] start = new int[100];
private static int[] end = new int[100];
private static class Task implements Runnable{
int idx;
public Task(int idx) {this.idx=idx;}
@Override
public void run() {
try {
int i = index.getAndIncrement();
start[idx] = i;//System.out.println("start"+idx+" =====>"+i);
queue.put(""+i);
end[idx] = i;//System.out.println("end "+idx+" =====>"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
for(int i = 0;i<100;++i){
new Thread(new Task(i), ""+i).start();
//如果不睡眠, 結果會相對隨機, 因爲線程創建時間差不多, 操作系統調度優先級差不多
//如果睡眠, 因爲創建時間不同, 而線程一直阻塞等待, 那麼由於linux等操作系統, 在喚醒線程的時候, 阻塞時間越長的優先級越高, 所以會按照線程創建順序喚醒
//Thread.sleep(50);
}
Thread.sleep(200); // 等待一段時間, 需要超過自旋時間
for(int j = 0;j<100;j++){
queue.take();
}
for(int i=0; i<100; i++){
System.out.println(start[i] + " " + end[i]);
}
}
}