synchronizedemo4.java
来自「JAVA程序设计课程中各章节的程序实例。」· Java 代码 · 共 113 行
JAVA
113 行
/**
*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 + =
减小字号Ctrl + -
显示快捷键?