📄 wait-notify.java
字号:
class SyncStack
{
private int index=0;
private int buffer[]=new int[3];
public synchronized void push(int i)
{
while(index==buffer.length)
{
try { wait(); }
catch(InterruptedException e){ }
}
notify();
buffer[index]=i;
System.out.println("Produced:"+i);
index++;
}
public synchronized int pop()
{
while(index==0)
{
try { wait(); }
catch(InterruptedException e){ }
}
notify();
index--;
System.out.println("Consumed:"+buffer[index]);
return buffer[index];
}
}
class Producer implements Runnable
{
SyncStack theStack;
public Producer(SyncStack s)
{ theStack=s; }
public void run()
{
int num=0;
while(true)
{
num++;
theStack.push(num);
try { Thread.sleep(100); }
catch(InterruptedException e){ }
}
}
}
class Consumer implements Runnable
{
SyncStack theStack;
public Consumer(SyncStack s)
{ theStack=s; }
public void run()
{
while(true)
{
int i=theStack.pop();
try
{
if(i<5)
Thread.sleep(1000);
else
Thread.sleep(50);
}
catch(InterruptedException e){ }
}
}
}
class SyncTest
{
public static void main(String args[])
{
SyncStack stack =new SyncStack();
Producer prod=new Producer(stack);
Consumer cons=new Consumer(stack);
Thread t1=new Thread(prod);
Thread t2=new Thread(cons);
t1.start();
t2.start();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -