这样真的中断线程了吗?

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)的代码,对不对?

不知道我的理解是否正确,请各位大吓指正!


...全文
213 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ohuan 2007-08-03
  • 打赏
  • 举报
回复
好象明白了。。。
叩谢!
hanxd106 2007-07-28
  • 打赏
  • 举报
回复
关注一下
codeartisan 2007-07-28
  • 打赏
  • 举报
回复
线程离开了run方法意味着这个线程的终止。


“没有任何语言方面的需求要求一个被中断的线程应该终止。
中断一个线程只是为了引起该线程的注意 ,被中断线程可以决定如何应对中断。”这是core java2中的原话。
popeyely 2007-07-28
  • 打赏
  • 举报
回复

在(1)中,把stop置为true 了后,确实可以不进入循环,但是这样线程真的中断了吗?只能说这个时候不进入(2)这个循环而已吧?其实run()这个方法应该还在运行中吧?也就是说这个线程没有真正意义上的中断。
——————————————————————————————————————————
当sotp设置成true以后就跳出while循环了。。然后执行输出语句。。执行完后线程结束。。。




如果把(3)改成
while(true){

System.out.println("Thread exiting under request..."); //(4)

}

那还会继续执行(4)的代码,对不对?
——————————————————————————————————————
如果这样改。。。线程就不会终止。。。而是一直满足。。一直死循环了。。
zhl0369 2007-07-25
  • 打赏
  • 举报
回复
run方法在出了while后,再运行第(3)句,然后就结束了啊
这时线程也就结束了
你可以这样看线程的状态。

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...");

System.out.println("1"+thread.getState());
thread.start();

System.out.println("2"+thread.getState());
Thread.sleep(3000);

System.out.println("Asking thread to stop...");

System.out.println("3"+thread.getState());
thread.stop = true; //(1)

System.out.println("4"+thread.getState());
Thread.sleep(3000);

System.out.println("5"+thread.getState());
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)

}

}


ohuan 2007-07-25
  • 打赏
  • 举报
回复
thread.getState()是什么方法啊?
还是没看出来。。。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧