package com.pengshi.ThreadTest;
public class SynchronizedTest {
private static int number = 0;
public synchronized void add() throws InterruptedException {
while (number != 0) {
this.wait();
}
number ++;
System.out.println(Thread.currentThread().getName() + " :: " + number);
this.notify();
}
public synchronized void decr() throws InterruptedException {
while (number != 1) {
this.wait();
}
number --;
System.out.println(Thread.currentThread().getName() + " :: " + number);
this.notify();
}
public static void main(String[] args) {
SynchronizedTest synchronizedTest = new SynchronizedTest();
new Thread(() -> {
for (int i = 0; i < 10; ++i) {
try {
synchronizedTest.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; ++i) {
try {
synchronizedTest.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
}
}