Java 멀티스레드 연습, 알람
2983 단어 Java 연습
package com.konghao.test;
//
public class Alarm implements Runnable {
private boolean isWork; //
public Alarm() {
super();
this.isWork = false; // ;
}
public boolean isWork() {
return isWork;
}
public void setWork(boolean isWork) {
this.isWork = isWork;
}
//
public void work(){
synchronized (this) {
// ,
if(isWork){
System.out.println("it's time for up!");
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
this.setWork(true);
work();
}
}
}
package com.konghao.test;
//
public class User implements Runnable{
private String name;
private Alarm myAlarm;
public User(String name, Alarm myAlarm) {
super();
this.name = name;
this.myAlarm = myAlarm;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Alarm getMyAlarm() {
return myAlarm;
}
public void setMyAlarm(Alarm myAlarm) {
this.myAlarm = myAlarm;
}
public void stopAlarm(){
synchronized (myAlarm) {
if(myAlarm.isWork()){
myAlarm.setWork(false);
System.out.println(this.name+" !");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
myAlarm.notify();
try {
myAlarm.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}else{
try {
myAlarm.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
while(true){
stopAlarm();
}
}
}
//
package com.konghao.test;
public class Test {
public static void main(String[] args) {
Alarm al = new Alarm();
User u = new User(" ",al);
Thread ut = new Thread(u);
Thread at = new Thread(al);
ut.setDaemon(true);
ut.start();
at.start();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java 멀티스레드 연습, 알람텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.