这样真的中断线程了吗?
ohuan 2007-07-25 09:11:18 class Example extends Thread {
volatile boolean stop = false;
public static void main(String args[]) throws Exception {
Example thread = new Example();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Asking thread to stop...");
thread.stop = true; //(1)
Thread.sleep(3000);
System.out.println("Stopping application...");
System.exit(0);
}
public void run() {
while (!stop) { //(2)
System.out.println("Thread is running...");
long time = System.currentTimeMillis();
while((System.currentTimeMillis() - time < 1000) && (!stop)) {
}
}
System.out.println("Thread exiting under request...");//(3)
}
}
在(1)中,把stop置为true 了后,确实可以不进入循环,但是这样线程真的中断了吗?只能说这个时候不进入(2)这个循环而已吧?其实run()这个方法应该还在运行中吧?也就是说这个线程没有真正意义上的中断。
如果把(3)改成
while(true){
System.out.println("Thread exiting under request..."); //(4)
}
那还会继续执行(4)的代码,对不对?
不知道我的理解是否正确,请各位大吓指正!