使用Thread.start()启动一个线程很简单.停止线程可以像设置在run方法中异步检查的标志一样简单,但可能需要包含对Thread.interrupt()的调用.暂停线程更有问题,但也可以使用一个标记来处理run方法而不是进程.这是一些(未经测试的)代码:
class MyThread extends Thread {
private final static int STATE_RUN = 0, STATE_PAUSE = 2, STATE_STOP = 3;
private int _state;
MyThread() {
_state = STATE_RUN;
}
public void run() {
int stateTemp;
synchronized(this) {
stateTemp = _state;
}
while (stateTemp != STATE_STOP) {
switch (stateTemp) {
case STATE_RUN:
// perform processing
break;
case STATE_PAUSE:
yield();
break;
}
synchronized(this) {
stateTemp = _state;
}
}
// cleanup
}
public synchronized void stop() {
_state = STATE_STOP;
// may need to call interrupt() if the processing calls blocking methods.
}
public synchronized void pause() {
_state = STATE_PAUSE;
// may need to call interrupt() if the processing calls blocking methods.
// perhaps set priority very low with setPriority(MIN_PRIORITY);
}
public synchronized void unpause() {
_state = STATE_RUN;
// perhaps restore priority with setPriority(somePriority);
// may need to re-establish any blocked calls interrupted by pause()
}
}
正如您所看到的,它可以很快变得复杂,具体取决于您在线程中所做的事情.