码迷,mamicode.com
首页 > 编程语言 > 详细

Java-J2SE学习笔记-线程-生产者消费者问题

时间:2015-06-29 13:00:48      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

一、概述

模拟生产者消费者问题

 

二、代码

1.Consumer.java

2.Producer.java

3.SyncStack.java

4.Test.java

 

1.Consumer.java

package ProducerConsumer;

public class Consumer implements Runnable {

	private SyncStack syncStack;
	
	
	public Consumer(SyncStack syncStack) {
		super();
		this.syncStack = syncStack;
	}

	public  void consume(){
		Product p; 
		for(int i = 0 ; i < 10 ; i++){
			p = syncStack.pop();
			System.out.println("******消费了:"+p);
		}
	}

	@Override
	public void run() {
//		try {
//			Thread.sleep(10);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		consume();
	}
}

  

2.Producer.java

package ProducerConsumer;

public class Producer implements Runnable {
	
	private SyncStack syncStack;
	
	public Producer(SyncStack syncStack) {
		super();
		this.syncStack = syncStack;
	}

	public  void produce(){
		for(int i = 0 ; i < 10 ; i++){
			Product p = new Product(i);
			syncStack.push(p);
			System.out.println("生产了:"+p);
		}
	}

	@Override
	public void run() {
		produce();
	}
}

  

3.SyncStack.java

package ProducerConsumer;

import java.util.ArrayList;
import java.util.List;

public class SyncStack {

	int index = 0;
	Product [] ps = new Product[6];
	//List<Product> ps = new ArrayList<Product>(); 
	
	public synchronized void  push(Product p) {
		//if(index == ps.length){ //不能用if判断,若用if,则this.wait()出现异常时,代码仍会往下执行
		while(index == ps.length){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		ps[index] = p;
		index = index + 1;
		//System.out.println(index);
	}
	
	public synchronized Product  pop() {
		while(index == 0){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		index --;
		return ps[index];
//		System.out.println("ps===="+ps);
//		Product p = ps.get(ps.size()-1);
//		ps.remove(ps.size()-1);
//		return p;
		
	}
}

  

4.Test.java

package ProducerConsumer;

public class Test {

	public static void main(String[] args) {
		SyncStack ss = new SyncStack();
		
		Producer p1 = new Producer(ss);
		Consumer c1 = new Consumer(ss);
		
		Thread tp1 = new Thread(p1); 
		Thread tc1 = new Thread(c1); 
		
		tc1.start();
		tp1.start();
		new Thread(new Producer(ss)).start();
		new Thread(new Consumer(ss)).start();
	}
}

  

三、运行结果

技术分享

四、小结

1.this.wait(),保有先锁定,才能调用wait,wait是使正在访问本对象的线程wait,且wait后此线程的锁会丢失,只有当线程醒来后才会再去找回锁。sleep则锁不会丢失。

2.this.notify()唤醒一个正在wait当前对象上的一个线程

Java-J2SE学习笔记-线程-生产者消费者问题

标签:

原文地址:http://www.cnblogs.com/shamgod/p/4607093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!