生产者、消费者问题之闹钟
需求:寫一個鬧鐘程序,鬧鐘每隔2秒響一次,每次響5聲,鬧鐘響鈴后1秒,人將鬧鐘關閉.
public class People implements Runnable {
private String name;
private Clock c;
public People(String name, Clock c) {
this.name = name;
this.c = c;
}
public void run() {
weakup();
}
public void weakup() {
//睡覺的人時刻等待鬧鈴響
while(true) {
synchronized(c) {
if(c.isRing()) {
c.setRing(false);
System.out.println("就起來了就起來");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
c.notify();
try {
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
c.setRing(true);
c.notify();
try {
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Clock1 getC() {
return c;
}
public void setC(Clock1 c) {
this.c = c;
}
}
?
?
public class Clock implements Runnable {
private boolean isRing; //判斷鬧鈴是否響過
public void run() {
ring();
}
public void ring() {
//鬧鈴響5次,每次響3聲
for(int i = 0; i < 5; i++) {
synchronized(this) {
if(!isRing) {
isRing = true;
for(int j = 0; j < 3; j++) {
System.out.println("叮叮叮...");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
try {
isRing = false;
this.notify();
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public boolean isRing() {
return isRing;
}
public void setRing(boolean isRing) {
this.isRing = isRing;
}
}
?
public class TestClockPeople {
public static void main(String [] args) {
Clock c = new Clock1();
People p = new People("大姚", c);
Thread ct = new Thread(c);
Thread pt = new Thread(p);
pt.setDaemon(true); //將人設置為守護線程
ct.start();
pt.start();
}
}
轉載于:https://www.cnblogs.com/helloworldlx/p/8550356.html
總結
以上是生活随笔為你收集整理的生产者、消费者问题之闹钟的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下安装Octave
- 下一篇: 取指周期的工作过程