进阶day06-等待唤醒功能实现(生产者与消费者)
This commit is contained in:
6
javaSE-day06/src/com/inmind/wait_notify08/BaoZi.java
Normal file
6
javaSE-day06/src/com/inmind/wait_notify08/BaoZi.java
Normal file
@@ -0,0 +1,6 @@
|
||||
package com.inmind.wait_notify08;
|
||||
//该类是包子类,它的功能是记录当前是否有包子,并用于线程间通信
|
||||
public class BaoZi {
|
||||
//包子的状态
|
||||
boolean flag = false;
|
||||
}
|
||||
30
javaSE-day06/src/com/inmind/wait_notify08/BaoZiPu.java
Normal file
30
javaSE-day06/src/com/inmind/wait_notify08/BaoZiPu.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.inmind.wait_notify08;
|
||||
//该类是包子铺类,它的功能是没有包子就做包子,有包子就等着(wait)
|
||||
public class BaoZiPu implements Runnable{
|
||||
BaoZi baoZi;
|
||||
|
||||
public BaoZiPu(BaoZi baoZi) {
|
||||
this.baoZi = baoZi;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(){
|
||||
while (true) {
|
||||
//任务:没有包子就做包子,有包子就等着
|
||||
synchronized (baoZi){
|
||||
if (baoZi.flag) {//true,有包子就等着
|
||||
//锁对象.wait方法实现线程等待的功能
|
||||
try {
|
||||
baoZi.wait();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} else {//fasle,没有包子就做,做完之后要通知吃货来吃
|
||||
System.out.println("包子铺做了一个包子");
|
||||
this.baoZi.flag = true;
|
||||
this.baoZi.notify();//唤醒另一个线程(吃货)来吃
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
javaSE-day06/src/com/inmind/wait_notify08/ChiHuo.java
Normal file
29
javaSE-day06/src/com/inmind/wait_notify08/ChiHuo.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.inmind.wait_notify08;
|
||||
//吃货类,任务是有包子就吃,没有就等着
|
||||
public class ChiHuo implements Runnable{
|
||||
BaoZi baoZi;
|
||||
|
||||
public ChiHuo(BaoZi baoZi) {
|
||||
this.baoZi = baoZi;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (true) {
|
||||
//任务是有包子就吃,没有就等着
|
||||
synchronized (baoZi) {
|
||||
if (baoZi.flag) {//true,有包子就吃
|
||||
System.out.println("吃货吃了一个包子");
|
||||
baoZi.flag = false;
|
||||
baoZi.notify();//吃完了包子,通知包子铺做包子
|
||||
} else {//false,没有就等着
|
||||
try {
|
||||
baoZi.wait();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
javaSE-day06/src/com/inmind/wait_notify08/Demo09.java
Normal file
15
javaSE-day06/src/com/inmind/wait_notify08/Demo09.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.inmind.wait_notify08;
|
||||
//测试类:创建包子,包子铺,吃货线程,让子线程运行起来
|
||||
public class Demo09 {
|
||||
public static void main(String[] args) {
|
||||
BaoZi baoZi = new BaoZi();//被包子铺,吃货线程共享,用来进行线程间通信
|
||||
//创建2个线程任务来实现2个线程按照我们所需的顺序来执行(一定是先有包子再吃)
|
||||
BaoZiPu baoZiPu = new BaoZiPu(baoZi);
|
||||
ChiHuo chiHuo = new ChiHuo(baoZi);
|
||||
|
||||
new Thread(baoZiPu).start();
|
||||
new Thread(chiHuo).start();
|
||||
|
||||
System.out.println("程序结束");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user