java 多線程(十七)

package com.thread.threadTest;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 阻塞隊列實現同步通知的功能
 * 阻塞隊列與semaphore有些類似,但也有不同,阻塞隊列是一方存放數據,
 * 另一方釋放數據,semaphore通常則是由同一方設置和釋放信號量
 *
 */
public class BlockingQueueCommunication {

    public static void main(String[] args) {
        final Business business = new Business();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<50;i++) {
                    business.sub(i);
                }
            }
        }).start();


        for (int i=0;i<50;i++) {
            business.main(i);
        }
    }

    static class Business{

        BlockingQueue<Integer> blockingQueueOne = new ArrayBlockingQueue<Integer>(1);
        BlockingQueue<Integer> blockingQueueTwo = new ArrayBlockingQueue<Integer>(1);

        //匿名構造方法,運行於在任何構造方法之前,創建幾個對象就會調用幾次
        {
            try {
                blockingQueueTwo.put(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //只有put和take方法才具有阻塞功能
        public void sub(int i){
            try {
                blockingQueueOne.put(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int j=1; j<=10; j++) {
                System.out.println("子線程第"+i+"次循環,循環第"+j+"次");
            }
            try {
                blockingQueueTwo.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void main(int i){
            try {
                blockingQueueTwo.put(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int j=1;j<=100;j++){
                System.out.println("主線程第" + i + "次循環,循環第" + j + "次");
            }
            try {
                blockingQueueOne.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章