Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Queue;
- import java.util.concurrent.BlockingQueue;
- import java.util.concurrent.LinkedBlockingDeque;
- import java.util.concurrent.ThreadLocalRandom;
- public class ProducerConsumerTest {
- public static void main(String[] args) {
- Container c = new Container();
- Producer p1 = new Producer(c);
- Consumer c1 = new Consumer(c);
- p1.start();
- c1.start();
- }
- }
- class Container {
- private BlockingQueue<Item> content;
- private boolean isEnd;
- public Container() {
- content = new LinkedBlockingDeque<>();
- isEnd = false;
- }
- public synchronized Queue<Item> content() {
- return content;
- }
- public synchronized boolean isEnd() {
- return isEnd;
- }
- public synchronized void setEnd(boolean end) {
- isEnd = end;
- }
- }
- class Consumer extends Thread {
- private Container container;
- private int size;
- private int count;
- public Consumer(Container container) {
- this.container = container;
- this.count = 0;
- this.size = 0;
- }
- public void run() {
- while (!container.isEnd() || !container.content().isEmpty()) {
- synchronized (container.content()) {
- if (!container.content().isEmpty()) {
- size += container.content().poll().weight;
- count++;
- if (count % 10 == 0) {
- System.out.println("Consumer readed " + count + " elements. Total size: " + size);
- }
- }
- }
- }
- System.out.println("Consumer readed " + count + " elements. Total size: " + size);
- }
- }
- class Producer extends Thread {
- private Container container;
- private int count;
- public Producer(Container container) {
- this.container = container;
- this.count = 0;
- }
- public void run() {
- try (BufferedReader br = new BufferedReader(new FileReader("towary.txt"))) {
- String line;
- while ((line = br.readLine()) != null) {
- String[] s = line.split("\\s");
- Item item = new Item(Integer.valueOf(s[0]), Integer.valueOf(s[1]));
- container.content().add(item);
- count++;
- if (count % 5 == 0) {
- //System.out.println("Producer putted " + count + " elements.");
- }
- }
- br.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.out.println("Producer putted " + count + " elements.");
- container.setEnd(true);
- }
- }
- class Item {
- protected int id;
- protected int weight;
- public Item(int id, int weight) {
- this.id = id;
- this.weight = weight;
- }
- @Override
- public String toString() {
- return "ITEM(" + id + "," + weight + ")";
- }
- }
- class Generator {
- public static void main(String[] args) {
- try (BufferedWriter bw = new BufferedWriter(new FileWriter("towary.txt", false))) {
- for (int i = 0; i < 10000; i++) {
- bw.write(i + " " + ThreadLocalRandom.current().nextInt(0, 1000));
- bw.newLine();
- }
- bw.flush();
- bw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement