阻塞队列通信

/**
 * 
 * @描述: 阻塞队列通信 .
 * 死锁:http://www.360doc.com/content/11/0904/13/834759_145686705.shtml
 * @作者: Wnj .
 * @创建时间: 2017年5月16日 .
 * @版本: 1.0 .
 */
public class BlockingQueueCommunication {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        
        final Business business = new Business();
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                
                for (int i = 1; i <= 50; i++) {
                    business.sub(i);
                }
                
            }
        }).start();
        
        for (int i = 1; i <= 50; i++) {
            business.main(i);
        }
        
    }
    
    static class Business {
        
        BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
        
        BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
        
        //匿名构造方法,创建几个对象就会调用几次
        
        {
            Collections.synchronizedMap(null);
            try {
                System.out.println("xxxxxdfsdsafdsa");
                queue2.put(1);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        public void sub(int i) {
            try {
                queue1.put(1);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int j = 1; j <= 10; j++) {
                System.out.println("sub thread sequece of " + j + ",loop of " + i);
            }
            try {
                queue2.take();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        public void main(int i) {
            try {
                queue2.put(1);
            }
            catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            for (int j = 1; j <= 100; j++) {
                System.out.println("main thread sequece of " + j + ",loop of " + i);
            }
            try {
                queue1.take();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}

 

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