您的位置:首页 > 其它

【重点】生产者消费者(设置flag标记:最佳实践)多生产者多消费者(把if换成while)

2013-10-20 18:49 316 查看
生产者消费者问题(为什么要设置flag标记:类似一种编程模式)

package com.xiaozhi.threadinformation;
/*
* 生产者消费者
*/
public class Test3 {

public static void main(String[] args) {
Resource resource=new Resource();
Producer producer=new Producer(resource);
Consumer consumer=new Consumer(resource);
Thread thread1=new Thread(producer);
Thread thread2=new Thread(consumer);
thread1.start();
thread2.start();
}
}

class Resource{
private int num;
private boolean flag=false;
public synchronized void input()
{
if(flag)
try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}
num++;
System.out.println("商品生产-----------------"+num);
flag=true;
this.notify();
}
public synchronized void output()
{
if(!flag)
try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}
System.out.println("商品消费--------------------------"+num);
flag=false;
this.notify();
}
}

class Producer implements Runnable{

private Resource resource;

public Producer(Resource resource) {
super();
this.resource = resource;
}

@Override
public void run() {
while(true)
resource.input();
}
}

class Consumer implements Runnable{

private Resource resource;

public Consumer(Resource resource) {
super();
this.resource = resource;
}

@Override
public void run() {
while(true)
resource.output();
}
}
多生产者多消费者问题(为什么要把if改为while:当唤醒同方线程时,再次判断)

package com.xiaozhi.procon;
/*
* 多生产者多消费者
*/
public class Test {

public static void main(String[] args) {
Resource resource=new Resource();
Producer producer1=new Producer(resource);
Producer producer2=new Producer(resource);
Consumer consumer1=new Consumer(resource);
Consumer consumer2=new Consumer(resource);
Thread thread1=new Thread(producer1);
Thread thread2=new Thread(producer2);
Thread thread3=new Thread(consumer1);
Thread thread4=new Thread(consumer2);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}

class Resource{
private int num;
private boolean flag=false;
public synchronized void input()
{
while(flag)
try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}
num++;
System.out.println("商品生产-----------------"+num);
flag=true;
this.notifyAll();
}
public synchronized void output()
{
while(!flag)
try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}
System.out.println("商品消费--------------------------"+num);
flag=false;
this.notifyAll();
}
}

class Producer implements Runnable{

private Resource resource;

public Producer(Resource resource) {
super();
this.resource = resource;
}

@Override
public void run() {
while(true)
resource.input();
}
}

class Consumer implements Runnable{

private Resource resource;

public Consumer(Resource resource) {
super();
this.resource = resource;
}

@Override
public void run() {
while(true)
resource.output();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: