代码如下:
public class MyThread extends Thread {
private boolean suspend = false;
private String control = ""; // 只是需要一个对象而已,这个对象没有实际意义
public void setSuspend(boolean suspend) {
if (!suspend) {
synchronized (control) {
control.notifyAll();
}
}
this.suspend = suspend;
}
public boolean isSuspend() {
return this.suspend;
}
public void run() {
while (true) {
synchronized (control) {
if (suspend) {
try {
control.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
this.runPersonelLogic();
}
}
protected void runPersonelLogic() {
}
public static void main(String[] args) throws Exception {
MyThread myThread = new MyThread() {
protected void runPersonelLogic() {
System.out.println("myThead is running");
}
};
myThread.start();
Thread.sleep(3000);
myThread.setSuspend(true);
System.out.println("myThread has stopped");
Thread.sleep(3000);
myThread.setSuspend(false);
}
}
Java线程挂起与恢复

本文介绍了一个自定义的Java线程类MyThread,该类通过wait()和notifyAll()方法实现了线程的挂起与恢复功能。通过设置suspend标志来控制线程的运行状态,演示了如何在主线程中控制子线程的暂停与继续。
1559

被折叠的 条评论
为什么被折叠?



