【发布时间】:2009-12-14 15:55:15
【问题描述】:
我相信字符串池在方法完成后放弃了本地字符串
还是:
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 的指南,此代码基于本地字符串正确同步其线程。输出将始终为 AABB 或 BBAA。为什么?为什么 str String 比它的本地声明更长寿?
【问题讨论】:
标签: java string multithreading synchronization