`
zranye
  • 浏览: 25866 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

关于java的死锁DeadLock

    博客分类:
  • JAVA
阅读更多

    看scjp考题的时候,关于一道多线程题目,总是不能把它推成死锁,郁闷之下,一看答案,原来真的不是死锁,可是为什么我老是想要把它推成死锁呢?很明显,是没有学到家。所以,翻箱倒柜查完资料之后,写出一个死锁Demo,来确定自己确实知道了什么是死锁。

 

 

public class DeadLockDemo {

	public static void main(String[] args) {
		final String lock1 = "LOCK1";
		final String lock2 = "LOCK2";
		
		Thread t1 = new Thread(){
			public void run() {
				synchronized (lock1) {
					System.out.println("t1:Locking Source1");
					try {
						sleep(1500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (lock2) {
						System.out.println("t1:Locking Source2");
					}
				}
			}
		};
		
		Thread t2 = new Thread(){
			public void run(){
				synchronized (lock2) {
					System.out.println("t1:Locking Source1");
					try {
						sleep(1500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (lock1) {
						System.out.println("t2:Locking Source1");
					}
				}
			}
		};

                t1.start();
		t2.start();
	}
}

 

    /*Output:

 

t1:Locking Source1
t2:Locking Source2

    *///:~

    一个简单死锁的小小实例。


    关于“锁”还有点懵懂,希望以后能慢慢领悟。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics