溫馨提示×

如何暫停一個正在運行的線程

小云
91
2023-09-28 10:56:53
欄目: 編程語言

要暫停一個正在運行的線程,可以使用Thread類的suspend()方法將線程掛起,然后使用resume()方法恢復線程的執(zhí)行。

以下是一個示例代碼:

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();
}
}
}
// 線程的執(zhí)行邏輯
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();
// 線程暫停后執(zhí)行其他邏輯
System.out.println("Thread is paused");
// 恢復線程
runnable.resume();
// 線程恢復后繼續(xù)執(zhí)行
}
}

可以根據具體需求來判斷何時暫停和恢復線程的執(zhí)行。

0