多线程死锁问题简单案例

多线程案例其实也就是一句话,我获得一个线程资源不释放,又要获得另一个资源,
其他线程也是获得一个不释放,又想获得别的线程。其实最多的就是线程之间的相互调用。


/**
 * 指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。
 * 
 * @author Janle
 *
 */
public class 多线程死锁问题 {

	public static void main(String[] args) {
		/*****************************死锁案例1**************************************/
		ThreadDieSock run01 = new ThreadDieSock(1);
		ThreadDieSock run02 = new ThreadDieSock(0);
		Thread thread01 = new Thread(run01);
		Thread thread02 = new Thread(run02);
		 System.out.println("启动线程。。。");
		//thread01.start();thread02.start();
		
		/*****************************死锁案例2**************************************/
		//用main方法作为一个线程
		AA aa=new AA();
		BB bb=new BB();
		Thread t=new Thread (new Runnable() {
			@Override
			public void run() {
				bb.bar(aa);
			}
		});
		t.start();
		aa.foo(bb);
	}
}

/**
 * 线程死锁:死锁案例1
 * 
 * 一个线程锁定了一个资源A,而又想去锁定资源B;在另一个线程中,锁定了资源B, 而又想去锁定资源A以完成自身的操作,
 * 两个线程都想得到对方的资源,而不愿释放自己的资源,造成两个线程都在等待,而无法执行的情况。
 */
class ThreadDieSock implements Runnable {
	private int flag = 1;

	public ThreadDieSock(int flag) {
		this.flag = flag;
	}

	//记住这里一定是要两个共用的资源
	private static Object A = new Object(), B = new Object();

	@Override
	public void run() {
		if (flag == 1) {
			synchronized (A) {
				System.err.println("锁定了一个资源A。休息0.5秒后锁定B去!");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (B) {
					System.out.println("拥有A的线程锁定B");
				}
			}

		}
		if (flag == 0) {
			synchronized (B) {
				System.err.println("锁定了一个资源B。休息0.5秒后锁定A去!");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (A) {
					System.out.println("拥有B的线程锁定A");
				}
			}

		}
	}
}

/*****************************线程之间的方法相互的调用:死锁案例2**************************************/
class AA {
    public synchronized void foo(BB b) {
        System.out.println(Thread.currentThread().getName() + " 进入AA的foo");
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 试图调用BB的last");
        b.last();
    }
    public synchronized void last() {
        System.out.println("AA的last()");
    }
}
 
class BB{
    public synchronized void bar(AA a) {
        System.out.println(Thread.currentThread().getName() + " 进入BB的bar方法");
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 试图调用AA的last方法");
        a.last();
    }
    //在使用bb对象调用last时候已经有对象的锁了
    public synchronized void last() {
        System.out.println("BB的last()");
    }
}


猜你喜欢

转载自janle.iteye.com/blog/2289558