i am not sure what title should i give to this question. basically my question is how thread share variable in ints own instance class: for e.g please check below code :
public class MainJava {
public static void main(String[] args) throws InterruptedException {
MyThread obje1=new MyThread(25);
MyThread obje2=new MyThread(50);
Thread t1=new Thread(obje1);
t1.setName("Thread"+25);
t1.start();
Thread.sleep(2000);
Thread t2=new Thread(obje2);
t2.setName("Thread"+50);
t2.start();
}
}
class MyThread implements Runnable {
int i;
String threadName;
public MyThread(int i) {
this.i = i;
}
@Override
public void run() {
if (Thread.currentThread().getName().equals("Thread25")) {
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(i +" FOR THREAD : "+Thread.currentThread().getName());
}
}
in this thread , my assumption was Thread50 will overwrite value of i to 50 and subsequently Thread25 will be read value of i as 50. As i is instance variable and it will be shared between two threads. but output was 50 FOR THREAD : Thread50 25 FOR THREAD : Thread25 so i am confused about this outout. Can someone help me understand this. Thanks in advance