171113 Thread.wait(), Thread.notify() - RYUDONGJIN/Memo_wiki GitHub Wiki
Thread.wait() , Thread.notify()
- wait()λ©μλκ° νΈμΆλλ©΄ μ€νμ€μ΄λ threadλ block μνλ‘ λ€μ΄κ°λ€.
- block μνκ° λ threadλ notify()λ©μλλ₯Ό λ§λλ©΄ λ€μ running μνλ‘ λμκ°λ€.
public class practice {
private String knife = "κ³΅μ© μΉΌ";
private String board = "κ³΅μ© λλ§";
private boolean useAble = false;
public static void main(String[] args) {
practice p = new practice();
Thread mother = new Thread(new Runnable() {
@Override
public void run() {
synchronized(p.knife) {
System.out.println("μλ§" + p.knife + "μ€λΉμλ£");
p.useAble = true;
if(p.useAble) {
try {
p.knife.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (p.board) {
System.out.println("μλ§" + p.board + "μ€λΉμλ£");
}
}
}
});
Thread son = new Thread(new Runnable() {
@Override
public void run() {
synchronized(p.board) {
System.out.println("μλ€" + p.board + "μ€λΉμλ£");
synchronized(p.knife) {
System.out.println("μλ€" + p.knife + "μ€λΉμλ£");
p.knife.notify();
}
}
}
});
mother.start();
son.start();
}
}