Vikash Mishra Vikash Mishra - 4 months ago 10
Java Question

Output of a Multithreaded program

Hi I am trying to understand the output of the below code .As per my understanding the output may be different for First and Second thread.But when I have executed the below code many times I am still getting the same value for both thread.Can someone please throw some light whether I am wrong or right.

package com.vikash.Threading;

public class ThreadLocalExample {

public static class MyRunnable implements Runnable {

@SuppressWarnings("unused")
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
D d=new D();

@Override
public void run() {
//threadLocal.set( (int) (Math.random() * 100D) );
d.setX( (int) (Math.random() * 100D) );
//System.out.println(Thread.currentThread().getName()+" "+threadLocal.get());
System.out.println(Thread.currentThread().getName()+" "+d.getX());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
//System.out.println(Thread.currentThread().getName()+" "+threadLocal.get());
//System.out.println(Thread.currentThread().getName()+" "+d.getX());
}
}

public static void main(String[] args) throws InterruptedException {

MyRunnable sharedRunnableInstance = new MyRunnable();

Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);

thread1.start();thread1.setName("First");
thread2.start();thread2.setName("Second");;

thread1.join(); //wait for thread 1 to terminate
thread2.join(); //wait for thread 2 to terminate
}
}

Answer

This is because you are not synchronizing on d, so what happens is thread 1 sets X value, then thread 2 sets x value, then thread 1 prints value that was already reset by thread 2. Synchronize block makes sure the correct value is printed

synchronized (d) {
    d.setX((int) (Math.random() * 100D));
    System.out.println(Thread.currentThread().getName() + " " + d.getX());
}
Comments