我相信字符串池中拋棄本地字符串時,他們的方法完成字符串池是否需要本地變量?
然而:
public class TestPool implements Runnable{
/**
* @param args the command line arguments
*/
public void run() {
String str= "hello";
synchronized(str){
try {
System.out.print(Thread.currentThread().getName());
Thread.sleep(500);
System.out.print(Thread.currentThread().getName());
}
catch(InterruptedException e){
}
}
}
public static void main(String []args){
new Thread(new TestPool(),"A").start();
new Thread(new TestPool(),"B").start();
}
}
按照whizlabs指南,基於本地String此代碼正確地將其同步線程。輸出將始終爲AABB或BBAA。爲什麼?爲什麼str字符串超過了它的本地聲明?
+1(更新) - 馬上回來!「? – 2009-12-14 16:02:45
我應該多寫一遍:)希望我的最終文本也值得投票。 – 2009-12-14 16:06:02
引用是一個局部變量,但它指向的字符串不是。查看將聲明更改爲String str = new(「hello」)時會發生什麼? – andandandand 2009-12-14 16:24:50