---
title: "多线程--生产者消费者-"
author: "uusoft"
date: "2011-10-02T04:53:33Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-10-02T08:35:55Z"
id: 1184434
url: "https://uusoft.iteye.com/blog/1184434"
---

思考：1.为什么生产者和消费者中要使用while循环判断？ 使用while循环可以让被唤醒的线程每次都判断标记，保障数据的准确性。

2.为什么使用了notifyAll？ 因为需要唤醒对方线程（如生产者唤醒消费者），使用notify的话会出现只唤醒本方线程(如消费者唤醒消费者)，导致程序中的线程都处于等待状态。


```java
/*线程同步---生产一部电脑消费一部电脑*/
public class ComputerDemo
{
	public static void main(String args[])
	{
		Computer com=new Computer();
		Producer pro=new Producer(com);
		Consumer con=new Consumer(com);

		Thread t1=new Thread(pro);
		Thread t2=new Thread(pro);
		t1.setName("生产线程A");
		t2.setName("生产线程B");

		Thread t3=new Thread(con);
		Thread t4=new Thread(con);
		t3.setName("@@@@@消费线程C");
		t4.setName("@@@@@消费线程D");

		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}


class Computer
{
	private String name;
	private int count=1;
	private boolean flag=false;

	public synchronized void set(String name)//生产电脑
	{   
		while(flag)
		{
			 try
			 {
				this.wait();
			 }
			 catch (Exception e)
			 {
			 }
		}

		
		this.name=name+"--"+count++;
		System.out.println(Thread.currentThread().getName()+"生产"+this.name);
		flag=true;
		notifyAll();
		
	}

    public synchronized void out()//消费电脑
	{   
		while(!flag)
		{
			 try
			 {
				this.wait();
			 }
			 catch (Exception e)
			 {
			 }
		}
		System.out.println(Thread.currentThread().getName()+"消费"+this.name);
		flag=false;
		notifyAll();
	}
}


class Producer implements Runnable
{
	Computer com;
	public Producer(Computer com)
	{
		this.com=com;
	}

	public void run()
	{
		while(true)
		{
            com.set("电脑~~");
		}
	}
}

class Consumer implements Runnable
{
	Computer com;
	public Consumer(Computer com)
	{
		this.com=com;
	}

	public void run()
	{
		while(true)
		{
            com.out();
		}
	}
}
```