代码如下,注释写的非常详细,复制就能跑。
public class Test{
//用一个int变量来模拟缓冲区
private int work=0;
public static void main(String[] args) {
Sx01 sx01 = new Sx01();
//启动生产者
new Thread(()->{
try {
sx01.kz();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
//启动消费者
new Thread(()->{
try {
sx01.kb();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
private synchronized void kz() throws InterruptedException {
//在一个死循环里来跑,注意for(;;)是比while(true)的效率高的
for (;;){
//当缓冲区内可消费元素数量为5时,生产者休眠
if(work>=5){
System.out.println("不能整了");
//先唤醒在休眠!! 不然会出大问题
notifyAll();
wait();
}
System.out.println("kz"+work++);
}
}
private synchronized void kb() throws InterruptedException {
for (;;){
//当缓冲区内可消费元素数量为0时,消费者休眠
if(work<=0){
System.out.println("不能摆了");
notifyAll();
wait();
}
System.out.println("kb"+work--);
}
}
}