有一种线程叫Internal Thread(内置线程),它可以依赖在一个实现Runnable接口的Object内部,然后在这个Object内部构造一个内置的thread。然后通过另外一个线程实现对内置线程的调控。举个例子:
public class InternalThread implements Runnable{
private Thread internalThread;//内置线程
private volatile boolean noStopRequest;//内置线程运行开关
public InternalThread(){
noStopRequest = true;//默认自动运行
internalThread = new Thread(this);//绑定线程到这个Object
internalThread.start();//线程运行开始
}
public void run(){
if(Thread.currentThread()!=internalThread){
throw RuntimeException("only InternalThread can invoke run()");
}
while(noStopRequest){
System.out.println("internal thread is going...");
try {
Thread.sleep(700);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public static void main(String[] args){
InternalThread it = new InternalThread ();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
it.stopRequest();//结束内置线程的运行
}
}
这样,在一个object 内部就可以create a InternalThread,然后自己可以改变自己的状态。