Answer the question
In order to leave comments, you need to log in
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);
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question