java一个线程怎么让另一个马上暂停
比如两个线程(处理不同业务),一个线程怎么让另一个马上暂停(停止业务处理即可),找不到思路。我最多只能做到另一个线程执行完一个循环才能暂停。有人提供下思路吗,有源代码更好咯。
------解决思路----------------------
import java.util.concurrent.Semaphore;
public class Test {
public static void main(String[] args) {
final Semaphore available = new Semaphore(1);
final Thread t1 = new Thread() {
public void run() {
int i = 0;
while(true) {
try {
available.acquire();
System.out.println(++ i);
Thread.sleep(500L);
available.release();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
};
Thread t2 = new Thread() {
public void run() {
try {
Thread.sleep(1000L);
available.acquire();
System.out.println("暂停");
Thread.sleep(5000L);
available.release();
System.out.println("开始");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
t2.start();
}
}
------解决思路----------------------
Object的wait()和notifyAll()方法,使用这两个方法让线程暂停,并且还能恢复,只需要封装一下:
public abstract 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 abstract 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);
}
}
------解决思路----------------------
在任意一条指令处停止执行,这个估计很难实现。系统调度程序也只能是接受某些建议,而不会绝对服从。不过,这种突然刹车的需求有实际用处吗?