温馨提示×

如何暂停一个正在运行的线程

小云
86
2023-09-28 10:56:53
栏目: 编程语言

要暂停一个正在运行的线程,可以使用Thread类的suspend()方法将线程挂起,然后使用resume()方法恢复线程的执行。

以下是一个示例代码:

public class MyRunnable implements Runnable {
private boolean isPaused = false;
public synchronized void pause() {
isPaused = true;
}
public synchronized void resume() {
isPaused = false;
notify();
}
@Override
public void run() {
while (true) {
synchronized (this) {
while (isPaused) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 线程的执行逻辑
System.out.println("Thread is running");
}
}
}

在上述代码中,通过添加isPaused字段来控制线程的暂停和恢复。pause()方法将isPaused设置为trueresume()方法将isPaused设置为false并调用notify()方法来唤醒线程。

以下是如何使用上述代码暂停和恢复线程:

public class Main {
public static void main(String[] args) throws InterruptedException {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
// 暂停线程
runnable.pause();
// 线程暂停后执行其他逻辑
System.out.println("Thread is paused");
// 恢复线程
runnable.resume();
// 线程恢复后继续执行
}
}

可以根据具体需求来判断何时暂停和恢复线程的执行。

0