`
249009188
  • 浏览: 45391 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

生产者消费者问题

 
阅读更多

/**

 * 经典生产者消费者的问题

 * 

 * 生产者消费者是两个线程 在run方法里面告诉他们放到哪一个容器里面就可以了  注意容器的拿和放的方法需要加上关键字synchronized

 * 

 */


public class ProducterConsumer {

    public static void main(String[] args) {

	Container cr = new Container();

	Producter p = new Producter(cr);

	Consumer c = new Consumer(cr);

	//如果需要生产快一点可以改sleep的时间短一点 

	new Thread(p).start();

	new Thread(c).start();

	//如果是有很多生产者 则在Container的nachulai和fang方法里面需要改成notifyAll

    }

}


//产品

class Product{

    int id;

    Product(int id){

	this.id = id;

    }

    public String toString(){

	return "Producr :"+ id;

    }

}


//容器

class Container{

    int index = 0;

    //定义一个数组放产品

    Product[] ptArray = new Product[6]; 


    public synchronized void fang(Product p){

	//放入的动作

	while(index == ptArray.length){

	    try {

		this.wait();

	    } catch (InterruptedException e) {

		e.printStackTrace();

	    }

	}

	this.notify();

	ptArray[index] = p ;

	index ++ ;

	

    }


    public synchronized Product nachulai(){

	while(index == 0){

	    try {

		this.wait();

	    } catch (InterruptedException e) {

		e.printStackTrace();

	    } 

	}

	this.notify();

	index --;

	return ptArray[index];

    }


}


//生产者 做成线程更符合  把生产的东西方法放入run方法

class Producter implements Runnable{

    Container cr = null;

    Producter(Container cr){

	this.cr = cr;

    }

    public void run(){

	for (int i = 0; i 	    Product p = new Product(i);

	    cr.fang(p);

	    try {

		Thread.sleep(2);

	    } catch (InterruptedException e) {

		e.printStackTrace();

	    }

	    System.out.println("生产了--"+ p);

	    

	}

    }

}


//消费者 把生产的东西方法放入run方法

class Consumer implements Runnable{

    Container cr = null;

    Consumer(Container cr){

	this.cr = cr;

    }


    public void run(){

	for (int i = 0; i 	    Product p = cr.nachulai();

	    try {

		Thread.sleep(1000);

	    } catch (InterruptedException e) {

		e.printStackTrace();

	    }

	    System.out.println("消费了--"+ p);

	    

	}

    }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics