Advertisement
Guest User

ThreadCom.java

a guest
Dec 5th, 2012
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. class TickTock {
  2.     String state;
  3.  
  4.     synchronized void tick(boolean running) {
  5.         if (!running) {
  6.             state = "ticked";
  7.             notify();
  8.             return;
  9.         }
  10.  
  11.         System.out.print("Tick ");
  12.  
  13.         state = "ticked";
  14.        
  15.         notify();
  16.         try {
  17.             while(!state.equals("tocked"))
  18.                 wait();
  19.         } catch (InterruptedException exc) {
  20.             System.out.println("Thread interrupted.");
  21.         }
  22.     }
  23.  
  24.     synchronized void tock(boolean running) {
  25.         if (!running) {
  26.             state = "tocked";
  27.             notify();
  28.             return;
  29.         }
  30.  
  31.         System.out.print("Tock ");
  32.        
  33.         state = "tocked";
  34.  
  35.         notify();
  36.         try {
  37.             while(!state.equals("ticked"))
  38.                 wait();
  39.         } catch (InterruptedException exc) {
  40.             System.out.println("Thread interrupted.");
  41.         }
  42.     }
  43. }
  44.  
  45. class MyThread implements Runnable {
  46.     Thread thrd;
  47.     TickTock ttOb;
  48.  
  49.     MyThread(String name, TickTock tt) {
  50.         thrd = new Thread(this, name);
  51.         ttOb = tt;
  52.         thrd.start();
  53.     }
  54.    
  55.     public void run() {
  56.         if (thrd.getName().compareTo("Tick") == 0) {
  57.             for (int i=0; i<5; i++) ttOb.tick(true);
  58.             ttOb.tick(false);
  59.         } else {
  60.             for (int i=0; i<5; i++) ttOb.tock(true);
  61.             ttOb.tock(false);
  62.         }
  63.     }
  64. }
  65.  
  66. class ThreadCom {
  67.     public static void main(String args[]) {
  68.         TickTock tt = new TickTock();
  69.         MyThread mt1 = new MyThread("Tick", tt);
  70.         MyThread mt2 = new MyThread("Tock", tt);
  71.  
  72.         try {
  73.             mt1.thrd.join();
  74.             mt2.thrd.join();
  75.         } catch (InterruptedException exc) {
  76.             System.out.println("Main thread interrupted.");
  77.         }
  78.         System.out.println();
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement