生產者消費者阻塞隊列版

package com.example.demo.test;

import ch.qos.logback.core.util.TimeUtil;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Test1 {

    ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);

    public void increament(){
        try {
            queue.put(1);
            System.out.println("生產---");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void decreament(){
        try {
            queue.take();
            System.out.println("消費---");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception{

        Test1 test1 = new Test1();
        for (int i=0;i<5;i++){
            new Thread(()->{
                test1.increament();
            }).start();
        }
        TimeUnit.SECONDS.sleep(1);
        for (int i=0;i<5;i++){
            new Thread(()->{
                test1.decreament();
            }).start();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章