Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2015
1,468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. public class WaitPuzzle {
  2.  
  3.     public static void main(String[] args) throws InterruptedException {
  4.         DoNothing doNothing = new DoNothing();
  5.         new WaitForever(doNothing).start();
  6.         new WaitForever(doNothing).start();
  7.         new WaitForever(doNothing).start();
  8.         Thread.sleep(100);
  9.         doNothing.start();
  10.         while(true) {
  11.             Thread.sleep(10);
  12.         }
  13.     }
  14.    
  15.    
  16.     static class WaitForever extends  Thread {
  17.        
  18.         private DoNothing doNothing;
  19.        
  20.         public WaitForever(DoNothing doNothing) {
  21.             this.doNothing =  doNothing;
  22.         }
  23.        
  24.         @Override
  25.         public void run() {
  26.             synchronized (doNothing) {
  27.                 try {
  28.                     doNothing.wait(); // will wait forever here as nobody notifies here
  29.                 } catch (InterruptedException e) {
  30.                     e.printStackTrace();
  31.                 }
  32.                 System.out.println("Unreachable Code");
  33.             }
  34.         }
  35.     }
  36.    
  37.     static class DoNothing extends Thread {
  38.  
  39.         @Override
  40.         public void run() {
  41.             System.out.println("Do Nothing ");
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement