阻塞队列ArrayBlockingQueue
package com.zwy.myThread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*模拟是一个放入数据一个取数据的过程,因为ArrayBlockingQueue是一个阻塞的队列
* ,当放入数据时候 ,队列已经满了队列会阻塞,
* 当取数据时候队列为空时候,队列会阻塞,这样就可以很好的模拟一个生产者消费者的问题了.
* 可以调整sleep的时间来查看队满,跟队空的情况
* */
public class BlockingQueueTest {
public static void main(String[] args) {
/*声明阻塞队列*/
final ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
ExecutorService service = Executors.newCachedThreadPool();
for(int i = 0 ; i < 2; i++){
Runnable run = new Runnable(){
public void run(){
while(true){
try{
Thread.currentThread().sleep(1000);
System.out.println(Thread.currentThread().getName()+":is ready to put data");
/*放入数据 ,生产线程产生产品*/
queue.put(1);
System.out.println(Thread.currentThread().getName()+"放入数据之后:队列长度为"+queue.size());
}catch(Exception e){
e.printStackTrace();
}
}
}
};
service.execute(run);
}
service.execute(new Runnable(){
public void run(){
while(true){
try{
Thread.currentThread().sleep(1000);
System.out.println(Thread.currentThread().getName()+":is ready to get data");
/*取入数据 ,生产线程消费产品*/
int i = (Integer) queue.take();
System.out.println(Thread.currentThread().getName()+":取出数据:"+i);
System.out.println(Thread.currentThread().getName()+"取出数据之后:队列长度为"+queue.size());
}catch(Exception e){
e.printStackTrace();
}
}
}
});
}
}