Tranvick

Untitled

Jun 13th, 2012
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1.  
  2. class Q {
  3.     boolean val = false;
  4.    
  5.     synchronized void values(int n) {
  6.         if (!val){
  7.             try {
  8.                 wait();
  9.             } catch (Exception e) {}
  10.         }
  11.         for (int i = n; i < n+5; ++i) System.out.println(i);
  12.         val = false;
  13.         notify();
  14.     }
  15.    
  16.     synchronized void text(String s) {
  17.         if (val)
  18.             try {
  19.                 wait();
  20.             } catch (Exception e) {}
  21.         System.out.println(s);
  22.         val = true;
  23.         notify();
  24.     }
  25. }
  26.  
  27. class producer implements Runnable {
  28.     Q q;
  29.     Thread t;
  30.     boolean live;
  31.    
  32.     producer (Q q) {
  33.         live = true;
  34.         Thread t = new Thread(this);
  35.         this.q = q;
  36.         t.start();
  37.     }
  38.    
  39.     public void run () {
  40.         q.text("BEFORE");
  41.         q.text("AFTER");
  42.     }
  43. }
  44.  
  45. class consumer implements Runnable {
  46.     Q q;
  47.     Thread t;
  48.     boolean live;
  49.    
  50.     consumer (Q q) {
  51.         live = true;
  52.         t = new Thread(this);
  53.         this.q = q;
  54.         t.start();
  55.     }
  56.    
  57.     public void run () {
  58.         q.values(0);
  59.         q.values(5);
  60.     }
  61. }
  62.  
  63. public class app {
  64.     public static void main(String args[]) {
  65.         Q q = new Q();
  66.         new producer(q);
  67.         new consumer(q);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment