package notify;
public class Bar {
public final int MAX_COUNT = 10;
public static int count = 0;
public static final Bar BAR_INSTANCE = new Bar();
private Bar() {
}
public void put() {
count++;
System.out.println(Thread.currentThread().getName()+"放置一份,剩余" + count + "份");
}
public void get() {
count--;
System.out.println(Thread.currentThread().getName()+"取走一份,剩余" + count + "份");
}
}
package notify;
public class Cooker implements Runnable {
Bar bar = Bar.BAR_INSTANCE;
@Override
public void run() {
while (true) {
synchronized (bar) {
if (Bar.count == 10) {
try {
bar.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
bar.put();
bar.notify();
}
}
}
}
}
package notify;
public class Waiter implements Runnable {
Bar bar = Bar.BAR_INSTANCE;
@Override
public void run() {
while (true) {
synchronized (bar) {
if (Bar.count == 0) {
try {
bar.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
bar.get();
bar.notify();
}
}
}
}
}
package notify;
public class Test {
public static void main(String[] args) {
Thread cooker = new Thread(new Cooker(), "厨师 ");
Thread waiter1 = new Thread(new Waiter(), "服务员1 ");
Thread waiter2 = new Thread(new Waiter(), "服务员2 ");
cooker.start();
waiter1.start();
waiter2.start();
}
}