I've been looking concurrency tutorials and I've stumbled upon the .join() method, which is used to make the current thread wait until the one that you joined ends, before continuing itself.
So I started experimenting. On one side I have.
public class Counter implements Runnable{
int count = 0;
public synchronized void increment(){
count++;
}
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
increment();
}
System.out.println(count);
}
}
And then the main class is:
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
System.out.println("Count: " + c.count);
}
}
The Count: c.count, is supposed to print the number at the end, but right now, it prints it right away, and it prints 0, because it prints before the threads even begin incrementing. And the threads themselves also print, but that's only for me to see how are they doing.
So the output is like
Count: 0
1942456
2000000
Which is to be expected, to fix this, I can just Add t1.join(); and t2.join(); so the main thread waits for t1 and t2 to finish counting, and then prints the final count. Now it looks like this:
Counter c = new Counter();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count: " + c.count);
And now the output is something like
1912345
2000000
Count: 2000000
So far, so good.
However, if instead of making the threads manually, I do it with a "for" loop, like this:
Counter c = new Counter();
for (int i = 0; i < 5; i++) { //make it count to 5 million just to have more threads
Thread th = new Thread(c);
th.start();
}
System.out.println("Count: " + c.count);
Now, it works like the first example without the joins, so it prints the "Count: xxxxx" before the threads finish incrementing, how do I .join() that? Doing th.join()
, I can't put th.join()
outside the "for" loop, and if I put it inside, then there's no multi-threading at all, because it makes all 5 threads execute sequentially, which solves the problem of the count being printed at the wrong time, but defeats all the purpose of multi-threading.