📄 synchronizedemo4.java
字号:
/**
*A advanced simple synchronize program
*2004.12.24. xhcprince
*/
class Q
{
int n;
boolean flag = false;
synchronized int get()
{
if(!flag)
{
try
{
wait(); //how much time will it wait?
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
this.n = n;
System.out.println("Get: " + n);
flag = false;
notify();
return n;
}
synchronized void put(int n)
{
if(flag)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
this.n = n;
flag = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable //don't forget to implements from Runnable!
{
Q obj;
Producer(Q obj)
{
this.obj = obj;
new Thread(this).start();
}
public void run()
{
int i = 0;
while(i <= 6)
{
obj.put(i);
++i;
}
}
}
class Consumer implements Runnable //don't forget to implements from Runnable!
{
Q obj;
Consumer(Q obj)
{
this.obj = obj;
new Thread(this).start();
}
public void run()
{
int t = 0;
while(t <= 6)
{
obj.get();
++t;
}
}
}
class SynchronizeDemo4
{
public static void main(String args[])
{
Q obj = new Q(); //the obj must be initialized explicitly!don't forget it!
new Producer(obj);
new Consumer(obj);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -