java线程入门C-P模式




package com.laotou99.backjack.test;

public class Producer implements Runnable {
	
	private Clerk clerk;

	public Producer(Clerk clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		System.out.println("Producer is product number....");
		for(int product =1;product<=10;product++){
			try {
				Thread.sleep((int)(Math.random()*3000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			clerk.setProduct(product);
		}
		
	}

}




package com.laotou99.backjack.test;

public class Consumer implements Runnable {
	private Clerk clerk;
	public Consumer(Clerk clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		System.out.println("consumer is get number....");
		for(int i=1;i<=10;i++){
			try {
				Thread.sleep((int)(Math.random()*3000));
			} catch (InterruptedException e) {
			 	e.printStackTrace();
			}
			int i1 = clerk.getProduct();
			System.out.println("i1-=>"+i1);
		}
	}

}



package com.laotou99.backjack.test;

public class Clerk {
	
	private int product = -1;
	
	public synchronized void setProduct(int product){
		if(this.product!=-1){
			try {
				wait();
			} catch (InterruptedException e) {
			 	e.printStackTrace();
			}
		}
		this.product=product;
		System.out.printf("product is set (%d)%n",this.product);
		notify();
	}
	
	public synchronized int getProduct(){
		if(this.product==-1){
			try {
				wait();
			} catch (InterruptedException e) {
			 	e.printStackTrace();
			}
		}
		int p = this.product;
		System.out.printf("consumer is get (%d)%n",this.product);
		this.product = -1;
		notify();
		return p;
	}
}


 

package com.laotou99.backjack.test;

public class Test1 {

	public Test1() {
	}

	public static void main(String[] args) {
		Clerk clerk = new Clerk();
		
		Thread producerThread = new Thread(new Producer(clerk));
		Thread consumerThread = new Thread(new Consumer(clerk));
		
		producerThread.start();
		consumerThread.start();
	}

}


你可能感兴趣的:(JAVA,设计模式)