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

发布时间:2025-12-11 01:31:36 浏览次数:2

要暂停一个正在运行的线程,可以使用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();}@Overridepublic void run() {while (true) {synchronized (this) {while (isPaused) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}}// 线程的执行逻辑System.out.println("Thread is running");}}}

在上述代码中,通过添加isPaused字段来控制线程的暂停和恢复。pause()方法将isPaused设置为true,resume()方法将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();// 线程恢复后继续执行}}

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

暂停线程
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477