Java线程导致死锁

标签 java multithreading concurrency locking

我正在尝试实现一些基本的启动、停止、暂停和恢复功能,这些功能允许我进行以下状态转换:

  • 停止运行
  • 运行停止
  • 运行到暂停
  • 暂停运行
  • 暂停到停止(导致死锁)

大部分都按预期工作,但最后的状态转换是不可能的,因为它会使线程卡住。有人可以向我解释为什么会发生这种情况以及如何预防吗?以下是代码的相关部分:

public class ThreadTest implements Runnable {

    private volatile boolean running = false;
    private volatile boolean paused = false;
    private Thread thread;

    public ThreadTest() {
        thread = new Thread(this);
    }

    public void run() {
        while (running) {
            try {
                if (paused) {
                    synchronized (this) {
                        while (paused)
                        wait(); 
                    }
                }   
            } 
            catch (InterruptedException e) {
            }
        }
    }

    public synchronized void start() {
        if(running && !thread.isAlive())
            return; 
        running = true;
        thread = new Thread(this);
        thread.start();
    }

    public synchronized void stop() {
        if(!running && thread.isAlive())
            return;  
        running = false;
        try {
            thread.join(); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         System.exit(0);    
    }

    public synchronized void resume() { 
        if(paused) {
        paused = false; 
        notify();
        }
        else {
            return;
        }
    }

    public synchronized void pause() { 
        if(!paused) {
            paused = true; 
            }
            else {
                return;
            } 
        }

}

最佳答案

wait(); 在 run 方法中将永远等待,因为这些不是 notify(); 当调用停止时,线程正在运行,因为永远等待,所以 thread.join() 将锁定。 您需要在 stop 或 wait for ever 中调用 notify 以 wait(1000);

关于Java线程导致死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16320309/

相关文章:

c# - 如何在 C# 中执行类似 Java 或 Qt 的多线程编程

Java并行同步2个线程

c++ - 并发内存访问减慢系统

c# - 以下代码/设计是否存在并发问题

java - 如何组装 SBT Scala 库以包含在 Java 7 Maven 项目中?

java - 在 JPA 中获取多对一关联时出现问题

java - 使用数组调用 PL/SQL 存储过程

java - 放置和弹出值堆栈的 Struts 2 拦截器是线程安全的吗?

java - Ratpack 的 Promise.cache 与 ParallelBatch 中的多个下游 promise

java - 如何使用 Java 从 Google Cloud Storage 下载文件?