java经典问题多线程死锁问题。因为多个线程都在等待根本不可能被释放的锁,从而导致所有的任务都无法继续运行下去。
在多线程下,“死锁”是必须避免的。
下面是死锁demo
package deadlock;
/**
* 这里使用的时嵌套等待锁,达到死锁现象。
*/
public class DealThreadimplements Runnable {
public Stringflag;
public lock1 =new Object(); //锁1
public lock2 =new Object(); //锁2
public void setFlag (String flag){
this.flag = flag; //标记
}
@Override
public void run() {
if(flag.equals("a")){
synchronized (lock1) {
try{
System.out.println("flag = " +flag);
Thread.sleep(3000); //让当前线程sleep3秒。
}catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("按lock1->lock2代码顺序执行");
}
}
}
if(flag.equals("b")){
synchronized (lock2) {
try{
System.out.println("flag = " +flag);
Thread.sleep(3000);
}catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("按lock2->lock1代码顺序执行");
}
}
}
}
}
package deadlock;
import deadlock.DealThread;
/**
* Created by tony on 2018/6/7.
*/
public class RunDealThread {
public static void main(String [] args){
try{
DealThread t1 =new DealThread();
t1.setFlag("a");
Thread thread1 =new Thread(t1);
thread1.start();
Thread.sleep(100);
t1.setFlag("b");
Thread thread2 =new Thread(t1);
thread2.start();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
flag = a
flag = b
两者的 System.out.println("按lockx->locky代码顺序执行");都没有输出。
线程1.得到锁lock1 进入方法,输出flag = a,该线程进入休眠3秒,三秒之后请求lock2,这段时间线程2得到lock2,并且运行输出flag = b,并且请求锁lock1。
这时:
持有 请求
线程1 lock1 lock2
线程2 lock2 lock1
两线程相互持有对方所请求的锁,这样就产生了死锁。
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x000000000371a968 (object 0x000000076b7e7188, a java.lang.Object),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x00000000037180d8 (object 0x000000076b7e7198, a java.lang.Object),
which is held by "Thread-1"
Java stack information for the threads listed above:
===================================================
"Thread-1":
at deadlock.DealThread.run(DealThread.java:41)
- waiting to lock <0x000000076b7e7188> (a java.lang.Object)
- locked <0x000000076b7e7198> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:745)
"Thread-0":
at deadlock.DealThread.run(DealThread.java:28)
- waiting to lock <0x000000076b7e7198> (a java.lang.Object)
- locked <0x000000076b7e7188> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:745)
Found 1 deadlock.
这是java堆栈的信息。