/** * @author Haiwei.tan * */ public class TestForThread2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //create the Clerk as a middleman Clerk clerk = new Clerk(); //create two threads, one as customer, and other as productor Thread t1 = new Thread(new Customer(clerk)); Thread t2 = new Thread(new Productor(clerk)); //start two threads t1.start(); t2.start(); } } class Clerk { //product number private int productNum = 0; //the max number which the shop can have final private int maxNum = 20; //create product,called by productor public synchronized void setProduct(int createNum) { while(this.productNum >= maxNum || (this.productNum + createNum) >maxNum) { try { //notice that there are not enough space for new product System.out.println("There so much products that we needn't produce any more!"); //wait for space wait(); } catch(InterruptedException e) { System.out.println("error occured when producing cakes!"); e.printStackTrace(); } } //add the new product this.productNum += createNum; System.out.printf("The product has created (%d) products %n", createNum); System.out.printf("We have (%d) products left %n", this.productNum); // 通知等待区中的一个消费者可以继续工作了 notify(); } //sell products,called by customer public synchronized void getProduct(int sellNum) { while(this.productNum < 0 || (this.productNum - sellNum) < 0) { try { //notice that there are no products can be sold System.out.println("There no products that we can't sell one!"); //wait for new product wait(); } catch(InterruptedException e) { System.out.println("error occured when selling cakes!"); e.printStackTrace(); } } //sell the product this.productNum -= sellNum; System.out.printf("The customer has bought (%d) products %n", sellNum); System.out.printf("We have (%d) products left %n", this.productNum); // 通知等待区中的一个生产者可以继续工作了 notify(); } } class Productor implements Runnable { Clerk clerk; public Productor(Clerk clerk) { this.clerk = clerk; } @Override public void run() { // TODO Auto-generated method stub System.out.println("The productor begins to create product......"); // 生产产品 while(true) { //do not need if your computer is not higher try { //sleep time Thread.sleep((int) (Math.random() * 3000)); }catch(InterruptedException e) { e.printStackTrace(); } //send the products to clerk clerk.setProduct((int) (Math.random() * 10)); } } } class Customer implements Runnable { Clerk clerk; public Customer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { // TODO Auto-generated method stub System.out.println("The customer begins to buy product......"); // 生产产品 while(true) { //do not need if your computer is not higher try { // 暂停随机时间 Thread.sleep((int) (Math.random() * 3000)); }catch(InterruptedException e) { e.printStackTrace(); } //get product from clerk clerk.getProduct((int) (Math.random() * 10)); } } }