Advertisement
palelipped

java13 (wait, notify(All))

Jul 30th, 2015
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. class Resourse {
  2.     private int res = 0;
  3.     private boolean isReady = false;
  4.  
  5.     synchronized void put(int res) {
  6.         while (isReady)
  7.             try {
  8.                 wait();
  9.             } catch (InterruptedException e) {
  10.                 e.printStackTrace();
  11.             }
  12.        
  13.         System.out.println("Положили: " + res);
  14.         this.res = res;
  15.        
  16.         isReady = true;
  17.         notifyAll();
  18.     }
  19.  
  20.     synchronized void get() {
  21.         while (!isReady)
  22.             try {
  23.                 wait();
  24.             } catch (InterruptedException e) {
  25.                 e.printStackTrace();
  26.             }
  27.        
  28.         System.out.println("Забрали: " + res);
  29.        
  30.         isReady = false;
  31.         notifyAll();
  32.     }
  33. }
  34.  
  35. class Producer implements Runnable {
  36.  
  37.     Resourse resourse;
  38.  
  39.     Producer(Resourse resourse) {
  40.         this.resourse = resourse;
  41.     }
  42.  
  43.     public void run() {
  44.         int i = 0;
  45.  
  46.         while (true) {
  47.             resourse.put(i++);
  48.         }
  49.  
  50.     }
  51.  
  52. }
  53.  
  54. class Customer implements Runnable {
  55.  
  56.     Resourse resourse;
  57.  
  58.     Customer(Resourse resourse) {
  59.         this.resourse = resourse;
  60.     }
  61.  
  62.     public void run() {
  63.         while (true) {
  64.             resourse.get();
  65.         }
  66.  
  67.     }
  68.  
  69. }
  70.  
  71. public class Test {
  72.  
  73.     public static void main(String args[]) throws Exception {
  74.         Resourse resourse = new Resourse();
  75.         Producer producer = new Producer(resourse);
  76.         Customer customer = new Customer(resourse);
  77.  
  78.         Thread thread1 = new Thread(producer);
  79.         Thread thread2 = new Thread(customer);
  80.  
  81.         thread1.start();
  82.         thread2.start();
  83.  
  84.         Thread.sleep(1000);
  85.         System.exit(0);
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement