No video

Race Condition | The Problem and It's Solution with Examples |

  Рет қаралды 563

Lazy Programmer

Lazy Programmer

Күн бұрын

Пікірлер: 3
@Werewolf5684
@Werewolf5684 2 ай бұрын
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); } }
@LazzyProgrammer
@LazzyProgrammer 2 ай бұрын
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 :)
@Werewolf5684
@Werewolf5684 2 ай бұрын
@@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
Race Conditions in Java Multithreading
22:39
Jakob Jenkov
Рет қаралды 32 М.
Get 10 Mega Boxes OR 60 Starr Drops!!
01:39
Brawl Stars
Рет қаралды 18 МЛН
Zombie Boy Saved My Life 💚
00:29
Alan Chikin Chow
Рет қаралды 24 МЛН
PEDRO PEDRO INSIDEOUT
00:10
MOOMOO STUDIO [무무 스튜디오]
Рет қаралды 12 МЛН
黑天使遇到什么了?#short #angel #clown
00:34
Super Beauty team
Рет қаралды 47 МЛН
Master Multithreading : Thread Pool In C++
20:19
CppNuts
Рет қаралды 9 М.
Java threads 🧵
16:01
Bro Code
Рет қаралды 110 М.
What is Mutex in C++ (Multithreading for Beginners)
12:29
CodeBeauty
Рет қаралды 42 М.
STOP Learning These Programming Languages (for Beginners)
5:25
Andy Sterkowitz
Рет қаралды 682 М.
Get 10 Mega Boxes OR 60 Starr Drops!!
01:39
Brawl Stars
Рет қаралды 18 МЛН