- package com.sergio.Thread;
- /**
- * @ClassName: DeadLock
- * @Description: 有两个对象a、b,有两个线程t1、t2。t1去锁a,同时t2去锁b;而同时t1又想去锁b,t2对象b的锁还没释放,t2又想去锁a,而t1对a的锁还没释放,最终造成死锁
- * @author Sergio Han
- * @date 2013-8-7 上午12:08:29
- *
- */
- public class DeadLock {
- public static void main(String[] args) {
- //创建两个对象
- Object o1 = new Object();
- Object o2 = new Object();
-
- //创建两个线程
- Thread t = new Thread(new T1(o1, o2));
- Thread t2 = new Thread(new T2(o1, o2));
-
- //启动
- t.start();
- t2.start();
- }
- }
- class T1 implements Runnable {
- //声明两个对象变量o1、o2
- Object o1;
- Object o2;
- //构造方法
- T1(Object o1, Object o2)
- {
- this.o1 = o1;
- this.o2 = o2;
- }
-
- //重写run方法
- public void run() {
- //锁o1对象的锁
- synchronized(o1)
- {
- try {
- //让t1线程休眠1秒
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //锁o2对象的锁
- synchronized (o2) {
- System.out.println("asfsf");
- }
- }
- }
- }
- class T2 implements Runnable {
-
- //声明两个对象变量o1、o2
- Object o1;
- Object o2;
- //构造函数
- T2(Object o1, Object o2)
- {
- this.o1 = o1;
- this.o2 = o2;
- }
- public void run() {
- //锁o2对象的锁
- synchronized (o2) {
- try {
- //让t2线程休眠1秒,防止没锁上
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //锁o1对象的锁
- synchronized (o1) {
- System.out.println("b");
- }
- }
- }
- }
复制代码 |