多线程

线程安全8 - 可阻塞的队列

2019-09-29  本文已影响0人  小超_8b2f
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockQueueTest {

    public static void main(String[] args) {
        final Business3 business = new Business3();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //子线程循环调用50次某逻辑
                for(int i = 0; i < 50; i++) {
                    business.sub(i);
                }
            }
        }).start();
        
        //主线程循环调用50次某逻辑
        for(int i = 0; i < 50; i++) {
            business.main(i);
        }
    }
}

class Business3 {
    BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<>(1);
    BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<>(1);
    
    {
        try {
            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 = 0; j < 10; j++)
            System.out.println("sub Thread run 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 e) {
            e.printStackTrace();
        }
        for (int j = 0; j < 10; j++)
            System.out.println("main Thread run sequece of " + j + " loop of " + i);
        
        try {
            queue1.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读