public class class_Q {
volatile boolean valueSet = false;
volatile int n;
synchronized int get()
{
System.out.println("Now i am in get block and valueset is : "+ valueSet );
if(!valueSet)
{
System.out.println("i am waiting in get block.....and releasing lock ");
try{
wait();
}catch(InterruptedException e)
{
System.out.println( "InterruptedException caught" );
}
}
System.out.println( " value of n now in get block is : " + n );
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
System.out.println(" Now i am in Put block and valueset is : "+ valueSet);
if(valueSet)
{
try
{
System.out.println("i am waiting in put block......and releasing lock. ");
wait();
}catch(InterruptedException e)
{
System.out.println( "InterruptedException caught" );
}
}
this.n = n;
valueSet = true;
System.out.println( "the value of n now in put block is : " + n );
notify();
}
}
class Producer implements Runnable{
class_Q q;
Producer(class_Q q)
{
this.q = q;
new Thread( this, "Producer" ).start();
}
public void run()
{
int i = 0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable{
class_Q q;
Consumer(class_Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class PCFixed {
public static void main (String args[])
{
class_Q q = new class_Q();
new Producer(q);
new Consumer(q);
System.out.println( "Press Control-C to stop." );
}
}
*输出**
现在我在 get 块中,valueset 是:false
我正在等待获取块.....并释放锁定
按 Control-C 停止。
现在我在 Put 块中,valueset 是:false
现在 put 块中 n 的值是:0
现在 get 块中 n 的值是:0
现在我在 get 块中,valueset 是:false
我正在等待获取块.....并释放锁定
现在我在 Put 块中,valueset 是:false
现在 put 块中 n 的值是:1
现在 get 块中 n 的值是:1
在我的输出的第六行之后,我期待 get() 线程唤醒(“notify()”)put() 线程。有人可以帮助我理解调用 get() 线程背后的逻辑(换句话说,为什么它在 get 块中?)