Java线程内存交互有关问题
阅读
public class TestThread implements Runnable{
public int t1 = 0;
public String s1 = new String("");
public List list = new ArrayList();
public void run(){
String threadName = Thread.currentThread().getName();
while (t1 == 0){
System.out.println(threadName + " is running");
}
System.out.println(threadName + " is end" + " list.get(0) = " + list.get(0));
System.out.println("s1 = " + s1);
}
public static void main(String args[]){
TestThread testThread = new TestThread();
testThread.list.add("start");
Thread t = new Thread(testThread);
try {
t.start();
Thread.currentThread().sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
testThread.list.add("End");
testThread.t1 = 1;
testThread.s1 = "123sdd";
}
}
... ... ... ...
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is end list.get(0) = start
s1 = 123sdd
在线程testThread启动后,更新基本类型和String(t1和s1)在线程运行时能实时传递,但list之类的对象就不行,
我记得线程启动后会生成一个工作内存,存放主内存的变量的一份拷贝,为什么t1和s1还能实时更新到线程中呢?
请教高手详细解释一下这三个变量和线程内存这间的交互。
------解决思路----------------------
我记得线程启动后会生成一个工作内存,存放主内存的变量的一份拷贝,为什么t1和s1还能实时更新到线程中呢?
t1,s1不是局部变量,更新是肯定的,只是时机的问题。一般遇到sysnchronized同步时,会进行更新。System.out.println中就有synchronized块,所以你在输出的时候会进行更新。
------解决思路----------------------
不存在“存放主内存的变量的一份拷贝”这个。
都是实时的,list.get(0)只能是start, list.get(1)才是end,没看见取。
阅读
上一篇:一个文件读写的有关问题 韩顺平的例题 下一篇:返回列表