如何构造一个死锁及处理方式
副标题[/!--empirenews.page--]
很简单,只要让线程1占有对象a的锁后,再去请求对象b的锁。与此同时,对象2已经占有了对象b的锁,再请求对象a的锁。线程1与线程2互相等待,形成了死锁。(在面试中,也会被经常地要求手写死锁) 代码如下: package com.example.dl;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController public class Controller {
@RequestMapping("/test") public String testDeadLock() {
final Object a = new Object(); final Object b = new Object();
new Thread(() -> { synchronized (a) { System.out.println(Thread.currentThread().getName() + "占有了对象a的锁"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "请求对象b的锁"); synchronized (b) { System.out.println(Thread.currentThread().getName() + "占有了对象b的锁"); } } }, "Thread 1").start();
new Thread(() -> { synchronized (b) { System.out.println(Thread.currentThread().getName() + "占有了对象b的锁"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "请求对象a的锁"); synchronized (a) { (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |