Java MultiThreading skips loop and gives wrong result
package Threading;
class DemoThread extends Thread{ //Thread Class
static int count=0; // variable incremented by both the threads
public DemoThread(String name) {
// TODO Auto-generated constructor stub
super(name);
}
public void run() {
for(int i=0;i<100000;i++) {
count++;
System.out.println(Thread.currentThread()+"Count"+count); // print thread operating on count variable
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class MyThreadClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
DemoThread t1=new DemoThread("T1");
DemoThread t2=new DemoThread("T2");
t1.start();
t2.start();
try {
t1.join();
t2.join(); //allowing both the threads to complee before main thread
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main Thread ends"+DemoThread.count); //final value of count
}
}
The final value of count should be 199998 but it is not giving the desired result. Why the threads are missing the loops ???
It happened because Thread T1 and T2 will update count at the same time (concurrency) like that:
Thread[T1,5,main]Count10
Thread[T2,5,main]Count10
Thread[T1,5,main]Count12
Thread[T2,5,main]Count12
Thread[T2,5,main]Count14
Thread[T1,5,main]Count14
Thread[T1,5,main]Count15
Thread[T2,5,main]Count16
You should use AtomicInteger
And update your code:
static int count=0; to static AtomicInteger count= new AtomicInteger();
count++; to count.incrementAndGet();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With