import java.util.concurrent.ConcurrentLinkedQueue;
public class T1 extends Thread {
private ConcurrentLinkedQueue<Integer>q; //拿不到就走
public T1(ConcurrentLinkedQueue<Integer>q){
this.q = q;
}
@Override
public void run() {
try {
q.add(1);
Thread.sleep(1000);
q.add(2);
Thread.sleep(2000);
q.add(3);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ConcurrentLinkedQueue;
public class T2 extends Thread {
private ConcurrentLinkedQueue<Integer>q;
public T2(ConcurrentLinkedQueue<Integer> q) {
this.q = q;
}
@Override
public void run() {
try {
Thread.sleep(1000); //不加這個會太快執行完導致都是nulll
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.poll());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentLinkedQueueTest {
public static void main(String[] args) {
ConcurrentLinkedQueue<Integer> q = new ConcurrentLinkedQueue<Integer>();
T1 t1 = new T1(q);
T2 t2 = new T2(q);
t1.start();
t2.start();
}
}
參考:http://www.itread01.com/articles/1476667313.html