多线程的同步与通信 [生产者消费者问题]

自己测试写了一下代码,考虑太复杂,死锁了.


重新更改后的代码,给大家参考:

package com.gyarmy.iotest2;

import java.beans.Customizer;


/**
 * 生产者 消费者的问题 
 * 共享数据: 产品数量
 * 线程的通信
 */

public class TestCusPro {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Clerk clerk = new Clerk();
		Producer p = new Producer(clerk);
		Consumer c = new Consumer(clerk);
		
		Thread t1 = new Thread(p);
		Thread t3 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.setName("生产者1:");
		t3.setName("生产者2:");
		t2.setName("消费者:");
		
		t1.start();
		t2.start();
		t3.start();
		
		

	}
}

class Producer implements Runnable{
	Clerk clerk;
	public  Producer(Clerk clerk) {
		// TODO Auto-generated constructor stub
		this.clerk = clerk;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("生产者生产产品");
		while(true){
			try {
				Thread.currentThread().sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			clerk.addProduct();
		}	
	}
}
class Consumer implements Runnable{
	Clerk clerk;
	
	public  Consumer(Clerk clerk) {
		// TODO Auto-generated constructor stub
		this.clerk = clerk;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("消费者购买产品");
		while(true){
			try {
				Thread.currentThread().sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			clerk.consumeProduct();
		}	
		
	}
}

class Clerk{
	int product = 0;
	
	public synchronized void addProduct(){
		if(product>=20){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			product++;
			System.out.println(Thread.currentThread().getName()+":"+"生产了第"+product+"个产品");
			notifyAll();
		}
	}
	
	public synchronized void consumeProduct(){
		if(product<=0)
		{
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			System.out.println(Thread.currentThread().getName()+":"+"消费了第"+product+"个产品");
			product--;
			notifyAll();
		}
		
	}
	
}

原文链接: 多线程的同步与通信 [生产者消费者问题] 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-38.html )

发表评论

0则评论给“多线程的同步与通信 [生产者消费者问题]”