45648

← разместить еще код

Расшаренный код:

package s15;

import java.util.concurrent.LinkedBlockingQueue;

public class Task1 {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue queue = new BlockingQueue(5);
        new Thread(new Producer(queue)).start();
        new Thread(new Consumer(queue)).start();
    }

    static class Producer implements Runnable {
        BlockingQueue queue;
        Message message = new Message();

        public Producer(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    queue.put(message.getName());
                }
            } catch (InterruptedException e) {
            }
        }
    }

    static class Consumer implements Runnable {
        BlockingQueue queue;

        public Consumer(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {

                while (true) {
                    queue.take();
                    System.out.println("Hello," + queue.take());
                }
            } catch (InterruptedException e) {
            }
        }
    }
}

class BlockingQueue {
    LinkedBlockingQueue queue = new LinkedBlockingQueue();
    int limit;

    public BlockingQueue(int limit) {
        this.limit = limit;
    }

    public synchronized void put(Object name) throws InterruptedException {
        while (this.queue.size() == this.limit) {
            wait();
        }
        if (this.queue.size() == 0) {
            notifyAll();
        }
        this.queue.add(name);
    }

    public synchronized Object take() throws InterruptedException {
        while (this.queue.size() == 0) {
            wait();
        }
        if (this.queue.size() == this.limit) {
            notifyAll();
        }
        Object name = this.queue.remove();
        return name;
    }
}

class Message {
    private String name = "Серж";

    public String getName() {
        return name;
    }