我是否需要添加以下代码的任何包才能成功执行?我在代码中遇到错误,我无法修复,特别是在使用synchronized
关键字时。谁能指出我做错了什么?谢谢。
数据对象:
class Q
{
int n;
boolean valueset=false;
synchronized int get()
{
if(!valueset)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception Caught.");
}
System.out.println("Got:"+n);
valueset=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueset)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception Caught.");
}
this.n=n;
valueset=true;
System.out.println("Put:"+n);
notify();
}
}
制片:
class Producer implements Runnable
{
Q q;
Producer(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
{
Q q;
Consumer(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)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}