黑马程序员技术交流社区
标题:
多线程问题
[打印本页]
作者:
莫运飞
时间:
2012-4-6 19:40
标题:
多线程问题
class ProduceDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
Producer pro= new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
Thread t3=new Thread(pro);
Thread t4=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}}
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name)
{
if(flag)
try{wait();}catch(Exception e){}
this.name=name+"........."+count++;
System.out.println(Thread.currentThread().getName()+"....生产者......"+this.name);
flag=true;
this.notify();
}
public synchronized void out(String name)
{
if(!flag)
try{wait();} catch(Exception e){}
this.name=name+"........."+count
;//有这条语句打印会调用“res.out("消费商品");”语句。
//掉这句话为什么会调用Producer类中的““res.set("商品");”呢?奇怪了 怎么会调用到Producer类中来?
System.out.println(Thread.currentThread().getName()+"....消费者......"+this.name);
flag=false;
this.notify();
}}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.set("商品");
}}}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.out("消费商品");
}}}
作者:
贠(yun)靖
时间:
2012-4-6 20:22
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name)
{
if(flag)
try{wait();}catch(Exception e){}
this.name=name+"........."+count++;
System.out.println(Thread.currentThread().getName()+"....生产者......"+this.name);
flag=true;
this.notify();
}
public synchronized void out(String name)
{
if(!flag)
try{wait();} catch(Exception e){}
this.name=name+"........."+count;
/*因为Producer中传递了一个Resources对象到它的构造方法Resource res中 并且调用了 Resources这个类中的set方法和out方法
* 两个方法都传了参数 而此时Producer中的res对象 就是Resources里面的this对象 关于this的应用在比老师
* 将this关键字的时候都说了 其中就说 this代表的调用本类方法或者变量的那个对象 */
System.out.println(Thread.currentThread().getName()+"....消费者......"+this.name);
flag=false;
this.notify();
}}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.set("商品");
}}}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.out("消费商品");
}}}
作者:
pray
时间:
2014-4-26 03:24
楼主表述之事与本人无关,只是本着“看贴回贴,繁荣网络、利人利己”的原则,为“保增长、扩内需、调结构,促民生”作出贡献,顺便赚3分。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2