class Resource
{
private String name;
private int count = 1;
public synchronized void set(String name)
{
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"......生产者...."+this.name);
}
public /*synchronized*/ void out()
{
System.out.println(Thread.currentThread().getName()+"....消费者...."+this.name);
}
}
class Producer implements Runnable
{
private Resource r ;
Producer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.set("面包");
}
}
}
class Consumer implements Runnable
{
private Resource r ;
Consumer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class ThreadDemo8
{
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);
t1.start();
t2.start();
}
}
这样编译会产生一个不解的运行结果:
生产----30
生产----31
生产----32
消费----30
这里线程t2中只有一句执行代码为什么cpu执行时还会被切换。
求大神告知,out()函数为什么也要加synchronized 同步?不是只有一句执行语句吗?
{
private String name;
private int count = 1;
public synchronized void set(String name)
{
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"......生产者...."+this.name);
}
public /*synchronized*/ void out()
{
System.out.println(Thread.currentThread().getName()+"....消费者...."+this.name);
}
}
class Producer implements Runnable
{
private Resource r ;
Producer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.set("面包");
}
}
}
class Consumer implements Runnable
{
private Resource r ;
Consumer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class ThreadDemo8
{
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);
t1.start();
t2.start();
}
}
这样编译会产生一个不解的运行结果:
生产----30
生产----31
生产----32
消费----30
这里线程t2中只有一句执行代码为什么cpu执行时还会被切换。
求大神告知,out()函数为什么也要加synchronized 同步?不是只有一句执行语句吗?