java-Object-wait-notify dome

package cn.testin.test.service.test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * lock test
 */
public class TestA {

    public static void main(String[] args){
        Runnable run = () -> {
            TestA a = new TestA();
            map.put(Thread.currentThread().getName(), a);
            a.myWait();
        };

        new Thread(run, "A").start();
        new Thread(run, "B").start();
        new Thread(run, "C").start();
        new Thread(run, "D").start();
        new Thread(run, "E").start();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(map);
        for (Map.Entry<String, TestA> entry : map.entrySet()) {
            entry.getValue().myNotify();
        }
    }

    private final AtomicInteger lock = new AtomicInteger(1);

    private final static Map<String, TestA> map =  new ConcurrentHashMap<>();

    private void myWait() {
        synchronized (this.lock) {
            try {
                System.out.println("incrementAndGet:" + this.lock.incrementAndGet());
                System.out.println("wait:"+ Thread.currentThread().getName());
                this.lock.wait();
                System.out.println("end:"+Thread.currentThread());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void myNotify(){
        if (this.lock.get() > 1) {
            synchronized (this.lock) {
                System.out.println("decrementAndGet:" + this.lock.decrementAndGet());
                System.out.println("notify:"+ Thread.currentThread().getName());
                this.lock.notify();
            }
        }
    }
}

执行结果:

incrementAndGet:2
incrementAndGet:2
incrementAndGet:2
wait:D
incrementAndGet:2
wait:A
wait:B
incrementAndGet:2
wait:C
wait:E
{A=cn.testin.test.service.test.TestA@22927a81, B=cn.testin.test.service.test.TestA@78e03bb5, C=cn.testin.test.service.test.TestA@5e8c92f4, D=cn.testin.test.service.test.TestA@61e4705b, E=cn.testin.test.service.test.TestA@50134894}
decrementAndGet:1
notify:main
decrementAndGet:1
end:Thread[A,5,main]
notify:main
end:Thread[B,5,main]
decrementAndGet:1
notify:main
end:Thread[C,5,main]
decrementAndGet:1
notify:main
end:Thread[D,5,main]
decrementAndGet:1
notify:main
end:Thread[E,5,main]
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值