编程语言
首页 > 编程语言> > java_死锁

java_死锁

作者:互联网

 

代码示例:

import java.util.concurrent.TimeUnit;

/**
 * 死锁:
 * 指两个或两个以上的线程在执行过程中,因争抢资源而造成的一种互相等待的现象,
 * 若无外力干涉那他们都将无法推进下去
 */
class HoldLockThread implements Runnable{
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){//锁住第一个参数
            System.out.println(Thread.currentThread().getName()+"\t 自己持有:"+lockA+"\t 尝试获得:"+lockB);
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            synchronized (lockB){//获取第二个参数
                System.out.println(Thread.currentThread().getName()+"\t 自己持有:"+lockB+"\t 尝试获得:"+lockA);
            }
        }
    }
}
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldLockThread(lockA,lockB),"A").start();
        new Thread(new HoldLockThread(lockB,lockA),"B").start();
    }
}

 

证明死锁:

标签:lockB,lockA,HoldLockThread,String,Thread,死锁,java,public
来源: https://www.cnblogs.com/jhdhl/p/14519013.html