这是毕老师的生产者消费者代码:似乎是解决了线程安全问题
看下我推算的1-7步骤,有没有哪里有问题,如果没有,那么这个程序是否还是有安全问题?
package test;
public class ProducerCustomerDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource res=new Resource();
Producer pro1=new Producer(res);
Producer pro2=new Producer(res);
Customer cus1=new Customer(res);
Customer cus2=new Customer(res);
new Thread(pro1).start();
new Thread(pro2).start();
new Thread(cus1).start();
new Thread(cus2).start();
}
}
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name)
{
while(flag) //3.pro1进来,flag为true,进入wait状态,此时pro2也进来,也进入wait状态
{
try
{
wait();
}
catch(Exception e)
{
}
} //6.假设唤醒的pro1取的CPU使用权,打印了生产者商品2后,pro1还没执行到flag=true这段代码,就被pro2抢得使用权
this.name=name+"--"+count++; //1.假设pro1先进来,打印生产者商品1后
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);//7.pro2打印生产者商品3
flag=true; //2.pro1将flag变为true
this.notifyAll();
}
public synchronized void out(String name)
{
while(!flag) //4.cus1进来,!flag为false,跳过该循环语句
{
try
{
wait();
}
catch(Exception e)
{
}
}
System.out.println(Thread.currentThread().getName()+"...消费者.."+this.name);
flag=false;
this.notifyAll(); //5.打印消费者商品1,并更改flag为false,并唤醒其他所有线程
}
}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.set("+商品+");
}
}
}
class Customer implements Runnable
{
private Resource res;
Customer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.out("+商品+");
}
}
}
|