诺,写给你看
public class LockInterruptly extends Thread{
public static ReentrantLock lock1=new ReentrantLock();
public static ReentrantLock lock2=new ReentrantLock();
int flag;
public LockInterruptly(String name,int flag){
super.setName(name);
this.flag=flag;
}
//在线程任务里构造死锁
@Override
public void run(){
try{
if(flag==1){
lock1.lockInterruptibly();
try{
Thread.sleep(500);
}catch (Exception e){
e.printStackTrace();
}
lock2.lockInterruptibly();
}else{
lock2.lockInterruptibly();
try{
Thread.sleep(500);
}catch (Exception e){
e.printStackTrace();
}
lock1.lockInterruptibly();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(lock1.isHeldByCurrentThread()){
lock1.unlock();
}
if(lock2.isHeldByCurrentThread()){
lock2.unlock();
}
System.out.println(Thread.currentThread().getId()+":线程退出");
}
}
public static void main(String[] args) throws InterruptedException {
LockInterruptly t1=new LockInterruptly("LockInterrupt1",1);
LockInterruptly t2=new LockInterruptly("LockInterrupt2",2);
t1.start();
t2.start();
Thread.sleep(1000);
}
}
怎么看死锁呢?先jps找到死锁的进程ID,如下
E:\temp1\test>jps
5568 LockInterruptly
18804 Launcher
3940 Jps
15000
可以找到对应的ID为5568
然后jstack指令
jstack -l 5568
可以看到下面的信息提示:
Java stack information for the threads listed above:
===================================================
"LockInterrupt2":
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000000d62d3268> (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.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:897)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
at com.example.demo.plaintest.LockInterruptly.run(LockInterruptly.java:32)
"LockInterrupt1":
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000000d62d3298> (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.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:897)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
at com.example.demo.plaintest.LockInterruptly.run(LockInterruptly.java:24)
Found 1 deadlock.
网友评论