1. Event using wait() and notify()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public class WaitNotify { public WaitNotify() { } public void waitEvent() throws InterruptedException { synchronized(this) { wait(); } } public void notifyEvent() throws InterruptedException { synchronized(this) { notify(); } } public static void main(String[] args) { WaitNotify wn = new WaitNotify(); Thread thread1 = new Thread( () -> { int i = 0; while(true) { try { wn.waitEvent(); System.out.println("Wake: " + i++); } catch (InterruptedException e) { } } }); Thread thread2 = new Thread( () -> { for( int i=0; i < 10; i++ ) { try { wn.notifyEvent(); Thread.sleep(100); } catch (InterruptedException e) { } } }); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { } } } |
Result:
Wake: 0 Wake: 1 Wake: 2 Wake: 3 Wake: 4 Wake: 5 Wake: 6 Wake: 7 Wake: 8 Wake: 9
댓글 없음:
댓글 쓰기