Vikash Mishra Vikash Mishra - 1 year ago 79
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 {

private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
D d=new D();

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 {
} 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.join(); //wait for thread 1 to terminate
thread2.join(); //wait for thread 2 to terminate

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download