`

用字符串做锁

    博客分类:
  • java
阅读更多
有些无聊,只是为了从侧面说明“XXX”字符串被intern后之后,所有具有相同值的“XXX”都指向堆中同一个对象。

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
分享到:
评论
1 楼 scanfprintf123 2009-11-15  
花花,你的设计模式怎么没有移动过来?

相关推荐

Global site tag (gtag.js) - Google Analytics