简单的死锁实现

代码实现

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLockDemo {

    private static Lock alock = new ReentrantLock();
    private static Lock block = new ReentrantLock();
    public static void main(String[] args) 
    {
        alock.lock();

        new Thread(new MyThread()).start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        block.lock();
        alock.unlock();

        block.unlock();
    }

    static class MyThread implements Runnable
    {
        @Override
        public void run()
        {
            block.lock();

            alock.lock();
            alock.unlock();

            block.unlock();
        }
    }
}

工具查看死锁
使用jps查看DeadLockDemo的进程号。

E:\PowerCmd>jps
5508 
3208 Jps
5880 DeadLockDemo
9384 

使用jstack -l 6396(DeadLockDemo的进程号),查看此进程的堆栈信息,如下所示。

Java stack information for the threads listed above:
===================================================
"Thread-0":
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000000d6054d18> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:836)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:870)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1199)
    at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:209)
    at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:285)
    at com.hyThread.DeadLockDemo$MyThread.run(DeadLockDemo.java:36)
    at java.lang.Thread.run(Thread.java:745)
"main":
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000000d6054d48> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:836)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:870)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1199)
    at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:209)
    at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:285)
    at com.hyThread.DeadLockDemo.main(DeadLockDemo.java:23)

Found 1 deadlock.

可以看到main线程和MyThread线程因为互相占有锁导致了死锁现象。

你可能感兴趣的:(简单的死锁实现)