can anyone please tell what is wrong with this code. output is not as expected. I am just counting by multiple threads using locking. I really did not understand what is the problem here. Expected and should be 10*100 => 1000 public class CountingProblem { private static int counter = 0; private static final ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) { for (int i = 0 ; i < 10 ; i++) { // 10 thread are running new Thread(() -> { for (int j = 0 ; j < 100 ; j++) { // each thread should increase it to 100 lock.lock(); // lock the section try { // run the critical section counter++; // increase the counter } finally { // unlock the lock lock.unlock(); } } }).start(); } System.out.println(counter); } }
@LazzyProgrammer2 ай бұрын
Multiple threads which you have created in the for loop are running in parallel to the main thread, but you are directly printing the value of counter after for loop, so there is a possibility that few of the threads might still be in execution when main thread gets the CPU and executed System.out.println(counter); which will result in incorrect output. So, before you print the final value of counter, please make sure that all the threads complete their execution. For that you can use a simple array of type Thread and add all newly created threads in that array during that for loop execution. And after that for loop, iterate through all the created Threads and using .join() make sure all threads have completed their execution. Once that is done only then print the final value of counter. I hope this is was helpful. Please do write your feedback :)
@Werewolf56842 ай бұрын
@@LazzyProgrammer aha got it so I need to print the counter value after end of all the threads has finished there job, thread.join(), that for the observation