Advertisement
Guest User

Untitled

a guest
May 5th, 2016
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. package nauka;
  2.  
  3. public class JDBC {
  4.  
  5.     public static void main(String[] args) {
  6.         Queue q = new Queue();
  7.         Author a = new Author(args, q);
  8.         Writer w = new Writer(args, q);
  9.         new Thread(a).start();
  10.         new Thread(w).start();
  11.     }
  12. }
  13.  
  14. class Author extends Thread {
  15.  
  16.     private String[] args;
  17.     private Queue q;
  18.  
  19.     public Author(String[] args, Queue q) {
  20.         this.args = args;
  21.         this.q = q;
  22.     }
  23.  
  24.     public void run() {
  25.         try {
  26.             sleep(1000);
  27.         } catch (InterruptedException e1) {
  28.             // TODO Auto-generated catch block
  29.             e1.printStackTrace();
  30.         }
  31.         for (int i = 0; i < 100; i++) {
  32.             q.put(args[i % args.length]);
  33.             // System.out.println("Producer #" + i + " put: " + args[i]);
  34.             try {
  35.                 sleep((int) (Math.random() * 100));
  36.             } catch (InterruptedException e) {
  37.             }
  38.         }
  39.  
  40.     }
  41. }
  42.  
  43. class Writer extends Thread {
  44.  
  45.     private String[] args;
  46.     private Queue q;
  47.  
  48.     public Writer(String[] args, Queue q) {
  49.         this.args = args;
  50.         this.q = q;
  51.     }
  52.  
  53.     public void run() {
  54.         for (int i = 0; i < 100; i++) {
  55.             q.get(args[i % args.length]);
  56.             System.out.println(args[i % args.length]);
  57.             try {
  58.                 sleep((int) (Math.random() * 100));
  59.             } catch (InterruptedException e) {
  60.             }
  61.         }
  62.  
  63.     }
  64. }
  65.  
  66. class Queue {
  67.     private String content;
  68.     private boolean available = false;
  69.  
  70.     public synchronized String get(String args) {
  71.         while (available == false) {
  72.             try {
  73.                 wait();
  74.             } catch (InterruptedException e) {
  75.             }
  76.         }
  77.         available = false;
  78.         notifyAll();
  79.         return content;
  80.     }
  81.  
  82.     public synchronized void put(String value) {
  83.         while (available == true) {
  84.             try {
  85.                 wait();
  86.             } catch (InterruptedException e) {
  87.             }
  88.         }
  89.         content = value;
  90.         available = true;
  91.         notifyAll();
  92.     }
  93.  
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement