Reputation: 21899
I have two classes. class Test
and class Application
. Test class implements Runnable
and is a thread..of course.
Both classes have public static void main.
First:
First I launch the Test
class in which there is a class level variable "a"
public static String a = "abc";
That points to a string object and Inside the Thread I am just assigning it a new value and printing that value.
Secondly:
I launch my Application
class that also have a main method and I just printed the Static String
in class Test
and surprisingly it prints "abc". Please note that I launched the second class after starting of my Test
class. Ideally it should print NULL
as because of Java Sandbox in which every process runs and one process should not access other process.
Now my question is why ? Why it shouldn't printed the new assigned String. I am giving both classes below
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author AZ
*/
public class Test implements Runnable {
public static String a = "abc";
@Override
public void run(){
while(true){
System.out.println(a);
a = new Date().toString();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
class ThreadRunner {
static public void main(String args[]){
new Thread(new Test()).start();
}
}
Second Class
import com.springhibernate.beans.MessageBean;
import com.springhibernate.beans.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author AZ
*/
public class Application {
public static void main(String args[]){
System.out.println("Test of printing String " + Test.a);
}
}
Upvotes: 0
Views: 78
Reputation: 887459
Each process has its own copy of the static field.
However, each process also runs the class intializer, so each copy of the field is intialized to abc
.
Upvotes: 3