0


JUC并发编程-生产者消费者实例

生产者消费者实例

1.ReentrantLock实现

publicclassDemo{publicstaticvoidmain(String[] args){Data data=newData();//两个生产者线程for(int i =0; i <2; i++){newThread(()->{try{
                    data.increment();}catch(InterruptedException e){
                    e.printStackTrace();}},"生产者"+String.valueOf(i)).start();}//两个消费者线程for(int i =2; i <4; i++){newThread(()->{try{
                    data.decrement();}catch(InterruptedException e){
                    e.printStackTrace();}},"消费者"+String.valueOf(i)).start();}}}classData{//共享资源privateint number=0;Lock lock=newReentrantLock();Condition condition= lock.newCondition();publicvoidincrement()throwsInterruptedException{//上锁
        lock.lock();try{//循环判断条件,不用if避免虚假唤醒while(number!=0){//不满足条件就等待
                condition.await();}//操作 生产
            number++;System.out.println(Thread.currentThread().getName()+"线程\t"+number);//通知唤醒等待的消费者线程
            condition.signalAll();}catch(InterruptedException e){
            e.printStackTrace();}//解锁
        lock.unlock();}publicvoiddecrement()throwsInterruptedException{//上锁
        lock.lock();try{while(number==0){
                condition.await();}

            number--;System.out.println(Thread.currentThread().getName()+"线程\t"+number);
            condition.signalAll();}catch(InterruptedException e){
            e.printStackTrace();}

        lock.unlock();}}

2.阻塞队列实现

publicclass 阻塞队列版 {publicstaticvoidmain(String[] args){MyResource myResource=newMyResource(newArrayBlockingQueue(10));newThread(()->{System.out.println("生产线程启动");try{
                    myResource.myProd();}catch(InterruptedException e){
                    e.printStackTrace();}},"Prod").start();newThread(()->{System.out.println("消费线程启动");try{
                    myResource.myConsumer();}catch(InterruptedException e){
                    e.printStackTrace();}},"Consumer").start();try{Thread.sleep(5000);System.out.println();System.out.println();System.out.println();System.out.println();

            myResource.stop();System.out.println("5秒时间到,老板main线程叫停");}catch(InterruptedException e){}}}classMyResource{//默认开启,开始生产消费privatevolatileboolean FLAG=true;privateAtomicInteger atomicInteger=newAtomicInteger();BlockingQueue<String> blockingQueue=null;publicMyResource(BlockingQueue blockingQueue1){
        blockingQueue=blockingQueue1;System.out.println(blockingQueue1.getClass().getName());}//生产方法publicvoidmyProd()throwsInterruptedException{String data=null;boolean result;while(FLAG){

           data=atomicInteger.incrementAndGet()+"";
           result=blockingQueue.offer(data,2L,TimeUnit.SECONDS);if(result){System.out.println(Thread.currentThread().getName()+"\t 插入队列"+data+"成功");}else{System.out.println(Thread.currentThread().getName()+"\t 插入队列"+data+"失败");}TimeUnit.SECONDS.sleep(1);}System.out.println("生产结束");}//消费方法publicvoidmyConsumer()throwsInterruptedException{String rs=null;while(FLAG){
             rs = blockingQueue.poll(2L,TimeUnit.SECONDS);if(rs==null||rs.equalsIgnoreCase("")){
                 FLAG=false;System.out.println(Thread.currentThread().getName()+"超过两秒钟没取到商品,退出");System.out.println();System.out.println();System.out.println();return;//}System.out.println(Thread.currentThread().getName()+"\t 消费队列"+rs+"成功");}}publicvoidstop(){this.FLAG=false;}}

本文转载自: https://blog.csdn.net/qq_50596778/article/details/122747682
版权归原作者 NeverOW 所有, 如有侵权,请联系我们删除。

“JUC并发编程-生产者消费者实例”的评论:

还没有评论