有些无聊,只是为了从侧面说明“XXX”字符串被intern后之后,所有具有相同值的“XXX”都指向堆中同一个对象。
运行结果(debug mode):
public class CPByStringTest {
public static class Consumer extends Thread {
@Override
public void run() {
long start = System.currentTimeMillis();
synchronized("lock"){
System.out.println("consumer get lock (ms)" + (System.currentTimeMillis() - start));
try {
System.out.println("sleep Consumer for 10 s");
sleep(10000);
System.out.println("wake up Consumer");
} catch (InterruptedException e) {
e.printStackTrace();
}
"lock".notifyAll();
}
}
}
public static class Producer extends Thread {
@Override
public void run() {
long start = System.currentTimeMillis();
synchronized("lock"){
System.out.println("Producer get lock (ms)" + (System.currentTimeMillis() - start));
try {
System.out.println("sleep producer for 10 s");
sleep(10000);
System.out.println("wake up producer");
} catch (InterruptedException e) {
e.printStackTrace();
}
"lock".notifyAll();
}
}
}
public static void main(String[] args) {
new Consumer().start();
new Producer().start();
}
}
运行结果(debug mode):
consumer get lock (ms)47
sleep Consumer for 10 s
wake up Consumer
Producer get lock (ms)10047
sleep producer for 10 s
wake up producer