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();
    }
}