package ThreadTest2;
// 线程通信的经典问题:生产者消费者//店员(资源)
class Clerk{private int productCount = 0 ;public synchronized void produceProduct() {if(productCount < 100 ) {++productCount;System.out.println(Thread.currentThread().getName()+":开始生产第"+ productCount + "个产品");notify();}else {try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public synchronized void comsumeProduct() {if(productCount > 0) {System.out.println(Thread.currentThread().getName() + ":开始消费第"+productCount + "个产品");productCount--;notify();}else {try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}class Producer extends Thread{private Clerk clerk;public Producer(Clerk clerk) {super();this.clerk = clerk;}public void run() {System.out.println( Thread.currentThread().getName()+":开始生产产品");while(true) {try {this.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}clerk.produceProduct();}}}class Customer extends Thread{private Clerk clerk;public Customer(Clerk clerk) {super();this.clerk = clerk;}public void run() {System.out.println(Thread.currentThread().getName()+":开始消费产品");while(true) {try {this.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}clerk.comsumeProduct();}}}public class ProductTest {public static void main(String[] args) {Clerk clerk = new Clerk();Customer c1 = new Customer(clerk);c1.setName("消费者1");Producer p1 = new Producer(clerk);p1.setName("生产者1");p1.start();c1.start();}
}