欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程(二)

程序员文章站 2022-05-31 14:16:09
...

线程一的基础进行改造

/**
 * 生产者和消费者案例   采用synchronized  wait()    nitifyall()
 * @author fanfan
 *
 */
public class TestProductorAndConsumer2 {

	public static void main(String[] args) {
		Clerk1 cle = new Clerk1();
		Productor1 pr = new Productor1(cle); 
		
		Consumer1 cr = new Consumer1(cle);
		
		new Thread(pr,"生产者A").start();
		new Thread(cr,"消费者B").start();
		
		new Thread(pr,"生产者A1").start();
		new Thread(cr,"消费者B1").start();
		
		new Thread(pr,"生产者A3").start();
		new Thread(cr,"消费者B3").start();
		
		
		new Thread(pr,"生产者A4").start();
		new Thread(cr,"消费者B4").start();
		
		new Thread(pr,"生产者A5").start();
		new Thread(cr,"消费者B5").start();
		
		new Thread(pr,"生产者A7").start();
		new Thread(cr,"消费者B7").start();
		
	}
}

class Clerk1{
	private int product = 0;
	//进货
	public synchronized void get() throws InterruptedException{
		while(product>=1){ //为了避免虚假唤醒问题,应该总是使用在循环中
			System.out.println("产品已满");
			this.wait();
		}
	    System.out.println(Thread.currentThread().getName()+";"+ ++product);
		this.notifyAll();
	}
	//卖货
	public synchronized void sale() throws InterruptedException{
		while(product <=0){
			System.out.println("缺货");
			this.wait();;
		}
		System.out.println(Thread.currentThread().getName()+":"+ --product);
		this.notifyAll();
		
	}
	
}

//生产者
class Productor1 implements Runnable{
	private Clerk1 clerk;
	
	public Productor1(Clerk1 clerk){
		this.clerk = clerk;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0;i<20;i++){
			try {
				Thread.sleep(200);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				clerk.sale();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

//消费者
class Consumer1 implements Runnable{

	private Clerk1 clerk;
	public Consumer1(Clerk1 clerk){
		this.clerk = clerk;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0;i<20;i++){
			try {
				clerk.get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
相关标签: 线程