BlockingQueue

/**
 * 
 * @描述:  队列(阻塞/非阻塞)、LinkedQueue不固定大小
 *   先进先出,如队列大小为8,如放进了8个数据,就不能继续放了,会进入阻塞,如果是非阻塞队列则会报错    
 *   
 *      Throwsexception    Special value()返回值判断   Blocks(阻塞)       Times out
Insert    add(e)              offer(e)                 put(e)             offer(e, time, unit)
Remove    remove()            poll()                   take()             poll(time, unit)
Examine   element()           peek()                   not applicable     not applicable

Java中的原子性,是指:原子操作是不能被线程调度机制中断的;操作一旦开始,它一定会在可能发生的“上下文切换”(即切换到其他线程执行)
之前执行完毕。 但是千万不要认为“原子操作不需要同步控制(这是错误的)”

 * @作者: Wnj .
 * @创建时间: 2017年5月16日 .
 * @版本: 1.0 .
 */
public class BlockingQueueTest {
    public static void main(String[] args) {
        final BlockingQueue queue = new ArrayBlockingQueue(3);
        for (int i = 0; i < 2; i++) {
            new Thread() {
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep((long)(Math.random() * 1000));
                            System.out.println(Thread.currentThread().getName() + "准备放数据!");
                            queue.put(1);//实现互斥,但不能保证打印是原子性的
                            System.out.println(Thread.currentThread().getName() + "已经放了数据," + "队列目前有" + queue.size() + "个数据");
                        }
                        catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                    }
                }
                
            }.start();
        }
        
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        //将此处的睡眠时间分别改为100和1000,观察运行结果
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName() + "准备取数据!");
                        queue.take();
                        System.out.println(Thread.currentThread().getName() + "已经取走数据," + "队列目前有" + queue.size() + "个数据");
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            
        }.start();
    }
}

 

posted @ 2017-05-25 12:27  superGG  阅读(232)  评论(0编辑  收藏  举报