Java多线程死锁问题
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
死锁问题
死锁定义
死锁举例
/**
* 线程死锁问题
*/
public class DeadLock {
public static void main(String[] args) {
//创建两个锁对象
Object lock1 = new Object();
Object lock2 = new Object();
//创建子线程
/*
线程1:①先获得锁1 ②休眠1s,让线程2获得锁2 ③线程1尝试获取锁2 线程2同理
*/
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
//线程1业务逻辑
synchronized(lock1){
System.out.println("线程1得到了锁子1");
try {
//休眠1s,让线程2先得到锁2
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1尝试获取锁2...");
synchronized(lock2){
System.out.println("线程1获得了锁2!");
}
}
}
},"线程1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
//线程2业务逻辑
synchronized(lock2){
System.out.println("线程2得到了锁子2");
try {
//休眠1s,让线程1先得到锁1;因为线程是并发执行我们不知道谁先执行
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2尝试获取锁1...");
synchronized(lock1){
System.out.println("线程2获得了锁1");
}
}
}
},"线程2");
thread1.start();
thread2.start();
}
}
如何排查死锁
死锁发生的条件
怎么解决死锁问题?
public class SolveDeadLock {
public static void main(String[] args) {
//创建两个锁对象
Object lock1 = new Object();
Object lock2 = new Object();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
//线程1业务逻辑
synchronized(lock1){
System.out.println("线程1得到了锁子1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1尝试获取锁2...");
synchronized(lock2){
System.out.println("线程1获得了锁2!");
}
}
}
},"线程1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
//线程2业务逻辑
synchronized(lock1){
System.out.println("线程2得到了锁子1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2尝试获取锁2...");
synchronized(lock2){
System.out.println("线程2获得了锁2");
}
}
}
},"线程2");
thread1.start();
thread2.start();
}
}
线程通讯机制(wait/notify/notifyAll)
定义
相关面试重点
LockSupport
LockSupport与wait()区别
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/weixin_44874269/article/details/116639326
锋哥最新SpringCloud分布式电商秒杀课程发布
👇👇👇
👆长按上方微信二维码 2 秒
感谢点赞支持下哈
评论