您的位置:首页 > 编程语言 > Java开发

JAVA 并发机制--生产者消费者问题

2015-02-19 11:00 369 查看
package ylj;

//生产者 消费者,线程同步问题

class Person  //定义一种商品

{
private String name = "杨露鉴";
private String content = "作者";
private boolean flag = false; //设置资源开关,为了实现 生产者生产一个 ,消费者消费一个的协调动作,避免了消费者 连续多次消费同一个资源状态
                             //true 表示消费者在消费 ,    false 表示生产者正在生产
public synchronized void set(String name,String content) //加入同步机制,使用了对象锁,保证了 资源数据结构set完整性,避免了生产者还未设置完全数据时候,消费者来消费
{
while(flag == true)  //观察到消费者正在消费,那么生产者就wait好了
{
try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
this.name = name;
try{
Thread.sleep(500);
}
catch(Exception e)
{
}
this.content = content;
this.flag = true; // 
notify();    //唤醒在门外等待的消费者,进门消费
}
public synchronized String get()             //当线程运行一个资源内的同步方法时,就会取得这个资源的锁
{ //同理,避免了消费者消费到一般数据时候,生产者马上更新了数据
while(flag == false)  //观察到生产者正在生产,那么消费者就wait好了

try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
String temp = this.name + " --> " + this.content;
this.flag = false; //消费者消费完毕,打开锁,同意生产者可以进来生产
notify();   //唤醒在门外等待的生产者
return temp;
}

}

class Pro implements Runnable //定义商品生产者
4000

{
private Person per = null;
public Pro(Person per)
{
this.per = per;
}
public void run()
{
for(int i=0;i<100;i++)  //生产者不断生产
{
if(i%2 == 0){
  per.set("csdn", "网站");
}
else
{
  per.set("杨露鉴", "作者");
}
}
}

}

class Cust implements Runnable //定义商品消费者

{
private Person per = null;
public Cust(Person per)
{
this.per = per;
}
public void run()  //消费者不断消费过程
{
for(int i=0;i<100;i++)  //不断消费
{
try{
Thread.sleep(100);
}
catch(Exception e)
{
}
   System.out.println(this.per.get());
}
}

}

public class MythreadRunnable{
public static void main(String[] args)
{
Person per = new Person();
Pro p = new Pro(per);
Cust c = new Cust(per);

new Thread(p).start();
new Thread(c).start();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: