`
minzaipiao
  • 浏览: 146356 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

再现java多线程的经典实例===生产者和消费者的问题

    博客分类:
  • Java
阅读更多
这两天用到了多线程,于是重新复习了一下,并且模拟了
多线程的经典例子生产者和消费者的问题。

Mobile  生产者生成的手机
SyncStack 用数组实现的栈 包括两个同步方法push (生产手机)和pop(消费手机)
两个实现了Runnable接口的线程类 生产者(Producer)和消费者 (Consumer)


public class ProducerConsumer
{

	public static void main(String[] args)
	{
		SyncStack ss = new SyncStack();
		Producer p = new Producer(ss);
		Consumer c = new Consumer(ss);
		new Thread(p).start();
		new Thread(c).start();
	}

}


class Mobile{
	int id;
	Mobile(int id){
		this.id = id;
	}
	public String toString(){
		return "手机:" +id;
	}
}


class SyncStack{
	int index = 0;
	Mobile[] arrayMobile = new Mobile[6];
	
	public synchronized void push(Mobile apple){
		if(index == arrayMobile.length){
			try
			{
				//生产完了,进行等待
				this.wait();
			}
			catch (InterruptedException e)
			{
			}
		}
		//通知消费者消费
		this.notify();
		arrayMobile[index] = apple;
		index ++;
	}
	
	public synchronized Mobile pop(){
		if(index == 0){
			try
			{
				//消费完了,进行等待
				this.wait();
			}
			catch (InterruptedException e)
			{
			}
		}
		//通知生产者生产
		this.notify();
		index --;
		return arrayMobile[index];
	}
}


class Producer implements Runnable{
	SyncStack ss = null;
	
	Producer(SyncStack ss){
		this.ss = ss;
	}
	public void run()
	{
		for(int i=0; i<20; i++){
			Mobile m = new Mobile(i);
			ss.push(m);
			System.out.println("生产了"+m);
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}


class Consumer implements Runnable{
	SyncStack ss = null;
	Consumer(SyncStack ss){
		this.ss = ss;
	}
	public void run(){
		for(int i=0; i<20; i++){
			Mobile m = ss.pop();
			System.out.println("消费了"+m);
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}
0
0
分享到:
评论
1 楼 east_java 2009-08-25  
有问题的代码

相关推荐

Global site tag (gtag.js) - Google Analytics