B
B
barabash20902022-01-23 17:35:11
Java
barabash2090, 2022-01-23 17:35:11

How to sum the output of two streams?

Good afternoon! Two streams output numbers from 1 to 10. The task is to sum the numbers that are output from the first stream with those that are output from the second stream. and output accordingly: 2, 4, 6, 8, 10, etc.

public class Example {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        CounterThread ct1 = new CounterThread(counter);
        ct1.start();

        CounterThread ct2 = new CounterThread(counter);
        ct2.start();

        Thread.sleep(1000);
    }
}

class Counter {
    private long counter = 0L;


    public void increaseCounter1() {
        counter++;

    }

    public long getCounter() {
        return counter;
    }
}

class CounterThread extends Thread
{
    private Counter counter;

    public CounterThread(Counter counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        for(int i=0; i<10; i++) {
            counter.increaseCounter1();
            System.out.println("Thread#1 " + i);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2022-01-24
@barabash2090

As it is written at you - in any way. Threads themselves call println, that is, they display it on the screen. And you won't do anything about it. It is necessary to make the threads communicate with another (main) thread, which will already perform data processing and display. For example, through queues.

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
 
public class Main {
 
    static class Task extends Thread {
 
        private final Queue<Integer> queue;
 
        public Task(Queue<Integer> queue) {
            this.queue = queue;
        }
 
        @Override
        public void run() {
            for (int i=0; i<=10; ++i) {
                queue.add(i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        final BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(100);
        final BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(100);
 
        final Thread thread1 = new Task(queue1);
        thread1.start();
        final Thread thread2 = new Task(queue2);
        thread2.start();
 
        while(true) {
            System.out.println(queue1.take() + queue2.take());
        }
 
    }
}

D
Dmitry Roo, 2022-01-23
@xez

As an option, use a common collection into which data from both streams will flow.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question