复制代码
package com.atgu;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class ShareDate1{
    private int num=0;
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (num!=0)
            {
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"==="+num);
            condition.signalAll();
            condition.signalAll();
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }

    }
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (num==0)
            {
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"==="+num);
            condition.signalAll();
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }

    }





}
public class produttorAndConsumer {


    public static void main(String[] args) {
        ShareDate1 shareDate1 = new ShareDate1();


        new Thread(
                ()->{
                    for (int i = 5; i > 0; i--) {
                        try {
                            shareDate1.increment();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }



                }
                ,"t1"
        ).start();

        new Thread(
                ()->{
                    for (int i = 5; i > 0; i--) {
                        try {
                            shareDate1.decrement();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }



                }
                ,"t2"
        ).start();



    }
}
复制代码

 

posted on   upupup-999  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!



点击右上角即可分享
微信分享提示