Not exactly:
T1's _tmp
is not shared with T2's _tmp
since they are distinct MyThread
's instances (not class' variables but instance's variables).
Indeed, you reinstantiate the whole class each time you create a thread:
new MyThread
It would be different if attributes were actually class variables:
static int _tmp = 10;
In this case you might need some synchronization mechanism (synchronized
block, or volatile
keyword or anything else adapted to the situation)
I would rephrase it to:
Method Arguments and Local Variable declared inside a method is Thread safe; both are exclusive for each invocation of the Thread.
However, a same instance of any class dealing with one or more global variables shares those ones among hitting threads.
It is a best practice to avoid the maximum of shared instances among threads, to avoid the need to synchronize everything (as long as performance/memory isn't too hurt).
Thus your code snippet follows the best practice :)
-----------COMMENT ABOUT YOUR ADDED CODE SNIPPET--------------:
MyThread _runn = new MyThread(); //you are using the same instance here ! delete this line
So, indeed, in this case the attribute would be share if you reuse this instance when declaring each thread:
Thread t1 = new Thread(_runn,"t1");
Thread t2 = new Thread(_runn,"t2");
Thread t3 = new Thread(_runn,"t3");
Replace by just:
Thread t1 = new Thread(new MyThread(), "t1"); //a new MyThread instance for each thread !
Thread t2 = new Thread(new MyThread(), "t2");
Thread t3 = new Thread(new MyThread(), "t3");
Will output (as expected :)):
_tmp = 10|t3
_tmp = 10|t1
_tmp = 20|t2