package thread.conAndpro;
public class Synchronized_Test {
public static void main(String[] args) {
Resouse_1 r=new Resouse_1();
Producer_1 p=new Producer_1(r);
Consumer_1 c=new Consumer_1(r);
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
new Thread(c).start();
}
}
class Resouse_1{
private int count;
Boolean flag=false;
public synchronized void produce(String name){
while(flag)
try {
this.wait();;
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"生产了"+(++count));
flag=!flag;
//我想问这地方如果消费者的两个线程都在wait()的话,生产者的一个线程将所有的线程都唤醒,是不是会造成
//消费者的两个线程都在运行,消费者的两个线程都判断标记为false,所以都往下执行,不就导致共享数据错误??、
this.notifyAll();
}
public synchronized void consume(String name){
while(!flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"消费了。。。。。。"+count);
flag=!flag;
this.notifyAll();
}
}
class Producer_1 implements Runnable{
private Resouse_1 r;
Producer_1(Resouse_1 r){
this.r=r;
}
public void run(){
while(true)
r.produce(Thread.currentThread().getName());
}
}
class Consumer_1 implements Runnable{
private Resouse_1 r;
Consumer_1(Resouse_1 r){
this.r=r;
}
public void run(){
while(true)
r.consume(Thread.currentThread().getName());
}
}
|