Don't get expected result for a streaming program

Below is the program:

import java.util.Date; 

public class ThreadLocalReplaceWithString {

    public static class MyRunnable implements Runnable {

        private String threadLocal = new String("");


        @Override
        public void run() {

           threadLocal= new Date().toString();       

           try {
                        Thread.sleep(4000); 
                  } catch (InterruptedException e) { e.printStackTrace(); }

           System.out.println(Thread.currentThread().getName()+
                               " start time = "+threadLocal);

        }
    }


    public static void main(String[] args) throws InterruptedException {
        MyRunnable myRunnable = new MyRunnable();

        Thread thread1 = new Thread(myRunnable,"Thread-1");
        Thread thread2 = new Thread(myRunnable,"Thread-2");

        thread1.start();
        Thread.sleep(1000); //Start thread-2 after 1 second.
        thread2.start();


    }

}

      

Outputs:

Thread-1 start time = Fri May 19 06:45:47 IST 2017
Thread-2 start time = Fri May 19 06:45:47 IST 2017

      

Why are the two time values ​​the same even though a new date is created every time I start a new thread. Is it because of the multi-core processor?

The program is taken from here

+3


source to share


2 answers


When you create one Runnable and pass a reference to it to two thread objects, it means that two threads are executing the same Runnable, they are changing the same object.

The run method sleeps for 4 seconds between setting an instance variable and printing it. The second stream starts in one second. Long time for the second thread to overwrite the instance variable with another line. When streams are printed they print the same value on the same Runnable.

What the writer of the article you linked to was that although the two threads were using the same Runnable instance, when the value is changed in ThreadLocal, each thread keeps its own value separately. The laid out code shows the opposite case, using a regular instance of a common Runnable member to show, on the other hand, why ThreadLocal is useful.



If you don't want threads to share state, give each one its own Runnable, or use ThreadLocal. Threadlocal is useful in cross-cutting situations for limiting an object to a thread, where you want different methods executed by the thread to access the same object without passing it explicitly. (There is a common scenario using threadlocal to store instances of the nondefaceafe SimpleDateFormat class.)

Don't reflexively address synchronization, many times the simplest answer is to avoid sharing.

+3


source


This is the expected result. The page you took the code from says:



ThreadLocal has been replaced with String. The Thread-1s threadLocal value has been overridden by the Thread-2s threadLocal value. So threadLocal was printing the same start time for both threads.

0


source







All Articles