▶ wait, notify, notifyAll에 의한 실행순서의 동기화
class NewsPaper {
String todayNews;
boolean isTodayNews = false;
public void setTodayNew(String news) {
todayNews = news;
isTodayNews = true;
synchronized(this) {
notifyAll(); // 모두 깨운다.
}
}
public String getTodayNews() {
if(isTodayNews == false){
try{
synchronized(this) {
wait(); // 기다려라.
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
return todayNews;
}
}
class NewsWriter extends Thread {
NewsPaper paper;
public NewsWriter(NewsPaper paper) {
this.paper = paper;
}
public void run() {
paper.setTodayNew("자바의 열기가 뜨겁습니다.");
}
}
class NewsReader extends Thread {
NewsPaper paper;
public NewsReader(NewsPaper paper) {
this.paper = paper;
}
@Override
public void run() {
System.out.println("오늘의 뉴스 : " + paper.getTodayNews());
}
}
public class NewsPaperStory {
public static void main(String[] args) {
NewsPaper paper = new NewsPaper();
NewsReader reader1 = new NewsReader(paper);
NewsReader reader2 = new NewsReader(paper);
NewsWriter writer = new NewsWriter(paper);
try {
reader1.start();
reader2.start();
Thread.sleep(1000);
writer.start();
reader1.join();
reader2.join();
writer.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
[Java]필터 스트림 (0) | 2012.09.24 |
---|---|
[Java]Byte File Copy 예제. (0) | 2012.09.23 |
[Java]동기화 기법 예제. (0) | 2012.09.20 |
[Java]Thread 예제 (0) | 2012.09.17 |
[Java]Iterator를 이용한 인스턴스의 순차적 접근 (0) | 2012.09.16 |
댓글 영역