Java多线程问题实例:死锁现象演示

原创 £神魔★判官ぃ 2024-09-21 17:09 155阅读 0赞

死锁是多线程编程中的一种严重问题,当两个或更多线程因争夺资源而造成的一种互相等待的现象时,就会出现死锁。

以下是一个简单的Java多线程死锁模拟示例:

  1. // 创建资源类
  2. class Resource {
  3. private int count = 1;
  4. // 获取资源的方法,如果当前资源数量小于2,会阻塞直到其他线程释放资源
  5. public synchronized void acquire() throws InterruptedException {
  6. while (count < 2) {
  7. wait();
  8. }
  9. count--;
  10. }
  11. // 释放资源的方法
  12. public synchronized void release() {
  13. count++;
  14. notifyAll();
  15. }
  16. }
  17. // 创建两个线程,每个线程尝试获取和释放资源
  18. public class DeadLockExample {
  19. private Resource resource1 = new Resource();
  20. private Resource resource2 = new Resource();
  21. public void startThreads() {
  22. Thread t1 = new Thread(() -> acquireResource(resource1)));
  23. Thread t2 = new Thread(() -> acquireResource(resource2)));
  24. t1.start();
  25. t2.start();
  26. }
  27. // 试图获取资源的方法
  28. private synchronized void acquireResource(Resource resource) throws InterruptedException {
  29. if (resource.acquire()) {
  30. System.out.println("Thread " + Thread.currentThread().getName() + " successfully acquired resource.");
  31. } else {
  32. throw new InterruptedException("Failed to acquire resource. Deadlock detected.");
  33. }
  34. }
  35. public static void main(String[] args) {
  36. DeadLockExample example = new DeadLockExample();
  37. example.startThreads();
  38. }
  39. }

在这个示例中,资源1和资源2分别由两个线程(t1和t2)管理。每个线程试图先获取资源再释放资源,这就可能导致死锁。

在main方法中,我们启动了这两个线程来演示死锁的发生过程。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,155人围观)

还没有评论,来说两句吧...

相关阅读