java-Object-wait-notify dome

  • Post author:
  • Post category:java


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]



版权声明:本文为Li_Cheng_Liang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。