Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package nauka;
- public class JDBC {
- public static void main(String[] args) {
- Queue q = new Queue();
- Author a = new Author(args, q);
- Writer w = new Writer(args, q);
- new Thread(a).start();
- new Thread(w).start();
- }
- }
- class Author extends Thread {
- private String[] args;
- private Queue q;
- public Author(String[] args, Queue q) {
- this.args = args;
- this.q = q;
- }
- public void run() {
- try {
- sleep(1000);
- } catch (InterruptedException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- for (int i = 0; i < 100; i++) {
- q.put(args[i % args.length]);
- // System.out.println("Producer #" + i + " put: " + args[i]);
- try {
- sleep((int) (Math.random() * 100));
- } catch (InterruptedException e) {
- }
- }
- }
- }
- class Writer extends Thread {
- private String[] args;
- private Queue q;
- public Writer(String[] args, Queue q) {
- this.args = args;
- this.q = q;
- }
- public void run() {
- for (int i = 0; i < 100; i++) {
- q.get(args[i % args.length]);
- System.out.println(args[i % args.length]);
- try {
- sleep((int) (Math.random() * 100));
- } catch (InterruptedException e) {
- }
- }
- }
- }
- class Queue {
- private String content;
- private boolean available = false;
- public synchronized String get(String args) {
- while (available == false) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- available = false;
- notifyAll();
- return content;
- }
- public synchronized void put(String value) {
- while (available == true) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- content = value;
- available = true;
- notifyAll();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement