📄 test1.java
字号:
public class Test1
{
public static void main(String[] args)
{
Hollow h = new Hollow();
Producer p = new Producer(h);
Consumer c = new Consumer(h);
p.start();
c.start();
}
}
class Producer extends Thread
{
Hollow h;
public Producer(Hollow h)
{
this.h=h;
}
public void run()
{
for (int i = 0; i<10; i++)
{
h.put(i);
System.out.println("put:"+i);
}
}
}
class Hollow
{
int value;
boolean flag=false;
//当方法中使用了wait() notify()方法时,此方法需要用synchronized来修饰
public synchronized void put(int value)
{
if(!flag)
{
this.value=value;
flag=true;
notify();
}
try {
wait();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public synchronized int get()
{
if(!flag)
{
try {
wait();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
flag=false;
notify();
return this.value;
}
}
class Consumer extends Thread
{
Hollow h;
public Consumer(Hollow h)
{
this.h=h;
}
public void run()
{
while(true)
System.out.println("get:"+h.get());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -