下面是我编写的生产者消费者代码,一共生成10条线程,但是线程操作次序很乱,我想实现的是每两条线程相互对应,依次生产和消费,
如01一组,23一组这样的执行,不知道有没有办法实现啊。坐等高手。
class Resource2{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
//加同步,保证线程安全
while(flag)//判断标记,为真等待
try {this.wait();} catch(InterruptedException e){}
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者"+this.name);
flag = true;
notifyAll();
}
public synchronized void get()
{
while(!flag)//判断标记,没有就等待
try{this.wait();}
catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
flag = false;
notifyAll();
}
}
class Producer implements Runnable
{
Resource2 r;
Producer(Resource2 r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.set("烤鸭");
}
}
}
class Consumer implements Runnable
{
Resource2 r;
Consumer(Resource2 r){
this.r = r;
}
public void run(){
while(true){
r.get();
}
}
}
public class DUO6
{
public static void main(String[] args) {
Resource2 r = new Resource2();
for(int x=0;x<5;x++)
{
new Thread( new Producer(r)).start();
new Thread(new Consumer(r)).start();
}
}
}
|