class Resource
{
private String name="烤鸭";
private int count = 1;
public void set()
{
name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产..."+this.name);
}
}
class Producer implements Runnable
{
Resource r =new Resource();
public void run()
{
while (true)
{
r.set();
}
}
}
class Test2
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer p = new Producer();
Thread t0 = new Thread(p);
t0.start();
}
}
第二组代码
class Resource
{
private String name;
private int count = 1;
public void set(String name)
{
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产..."+this.name);
}
}
class Producer implements Runnable
{
Resource r =new Resource();
public void run()
{
while (true)
{
r.set("烤鸭");
}
}
}
class Test3
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer p = new Producer();
Thread t0 = new Thread(p);
t0.start();
}
} 作者: 家进 时间: 2015-2-1 13:07
你好,恕我直言,你的代码有点乱,我将你的代码改动了一下,你对比一下就知道什么情况了,毕竟要自己思考的。
第一组代码:
class Resource
{
private String name="烤鸭";
int count = 100;
public void set()
{
System.out.println(Thread.currentThread().getName()+"...生产1..."+this.name+count--);
}
}
class Producer implements Runnable
{
Resource r =new Resource();
public void run()
{
while (r.count>0)
{
r.set();
}
}
}
class Test2
{
public static void main(String[] args)
{
Producer p = new Producer();
Thread t0 = new Thread(p);
t0.start();
}
}
第二组代码:
class Resource2
{
private String name;
int count = 100;
public void set(String name)
{
this.name = name;
System.out.println(Thread.currentThread().getName()+"..生产2.."+this.name+count--);
}
}
class Producer2 implements Runnable
{
Resource2 r =new Resource2();
public void run()
{
while (r.count>0)
{
r.set("烤鸭");
}
}
}
class Test3
{
public static void main(String[] args)
{
Producer2 p = new Producer2();
Thread t0 = new Thread(p);
t0.start();
}
} 作者: godmmm 时间: 2015-2-1 13:30
Test2 中的资源类你用的name=name+count 这的name相当于累加了
Test3 中的资源类你用的this.name=name;this.name+count--,这个this代表Producer2中的r对像,r.name在r对象创建时就是“烤鸭”,所以结果不一样。