package syn;
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer=new SynContainer();
Producter producter=new Producter(synContainer);
Consumer consumer=new Consumer(synContainer);
producter.start();
consumer.start();
}
}
//生产者
class Producter extends Thread{
SynContainer synContainer;
public Producter(SynContainer synContainer){
this.synContainer=synContainer;
}
@Override
public void run(){
for (int i = 0; i < 100; i++) {
try {
synContainer.producter();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consumer extends Thread{
SynContainer synContainer;
public Consumer(SynContainer synContainer){
this.synContainer=synContainer;
}
@Override
public void run(){
for (int i = 0; i < 100; i++) {
try {
synContainer.consumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SynContainer{
int count=0;
//生产者生产
public synchronized void producter() throws InterruptedException {
if(count==10){
this.wait();
}
count++;
System.out.println("生产者生产了第"+count+"只鸡");
this.notifyAll();
}
//消费者消费
public synchronized void consumer() throws InterruptedException {
if(count==0){
this.wait();
}
System.out.println("消费者消费了第"+count--+"只鸡");
this.notifyAll();
}
}
04-21
4239
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-18
05-09
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交