G
G
gleendo2017-03-05 10:00:08
Java
gleendo, 2017-03-05 10:00:08

Why is output not what is expected (Streams)?

Just trying to figure out multithreading.
Tried to make a small example:

public class App {
    public static final int N = 10_000_000;
    public static int counter = 0;

    public static void inc() {
        counter++;
    }

    public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();

        Thread t0 = new Thread(() -> {
            synchronized (obj) {
                for (int i = 0; i < N; i++) {
                    inc();
                }
            }
        });

        t0.start();

        Thread t1 = new Thread(() -> {
            synchronized (obj) {
                for (int i = 0; i < N; i++) {
                    inc();
                }
            }
        });

        t1.start();

//        t0.join();
//        t1.join();

        System.out.println(counter);
    }
}

Why without join(), the program does not run as expected? Made 2 threads. Inside, each has a synchronized block on the same object. I expected that it would work like this: Since they are synchronized on the same object, the threads will not interfere with each other. First, one will end, then another will start working. And as a result, the number 20_000_000 will be displayed. But now I don't know why it doesn't work the way I thought.
Explain how this program works. And what does the join method mean? I thought that it means that at first one will be completed then, then another will start working. Did I understand correctly? And why then does it not work as I described above, in my opinion, synchronization on one object is the same as waiting for the completion of another thread (in the example above).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Serkov, 2017-03-05
@evgeniy8705

t0 launched - it started the increment,
followed by t1,
and immediately printed, that's how many threads managed to count so many and output
if you remove the comment, the program waits for thread 0 to end, then starts thread 1, and then displays the result to the console

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question