public abstract class MyThread extends Thread {
private boolean suspend = false;
private int time;
private String control = ""; // 只是需要一个对象而已,这个对象没有实际意义
public BonreeThread(int time) {
this.time = time;
}
public void setSuspend(boolean suspend) {
if (!suspend) {
synchronized (control) {
control.notifyAll();
}
}
this.suspend = suspend;
}
public void run() {
while (true) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (control) {
if (suspend) {
try {
control.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
this.runPersonelLogic();
}
}
protected abstract void runPersonelLogic();
//测试主方法
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread(1000) {
@Override
protected void runPersonelLogic() {//这个方法会重复执行
System.out.println("执行");
}
};
myThread .start();
myThread .setSuspend(true);//阻塞bonreeThread内的runPersonelLogic()方法
myThread .setSuspend(false);//取消阻塞bonreeThread内的runPersonelLogic()方法
}
}