在Java中,可以使用以下方法安全地暂停线程:
public class MyThread extends Thread {
private volatile boolean isPaused;
public void pauseThread() {
isPaused = true;
}
public void resumeThread() {
isPaused = false;
synchronized (this) {
notify();
}
}
public void run() {
while (true) {
// 执行线程任务
// ...
// 检查是否需要暂停线程
while (isPaused) {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class MyThread extends Thread {
private boolean isPaused;
public synchronized void pauseThread() {
isPaused = true;
}
public synchronized void resumeThread() {
isPaused = false;
notify();
}
public void run() {
while (true) {
// 执行线程任务
// ...
// 检查是否需要暂停线程
synchronized (this) {
while (isPaused) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
这两种方法都使用一个boolean变量来标记线程是否需要暂停。当需要暂停线程时,将该变量设置为true,在线程的执行部分进行检查。若变量为true,则线程进入等待状态,直到被唤醒并且变量为false才会继续执行。暂停线程的方法通过设置boolean变量的值来实现,恢复线程的方法通过唤醒线程并设置boolean变量的值来实现。