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)的代码,对不对?不知道我的理解是否正确,请各位大吓指正!
在(1)中,把stop置为true 了后,确实可以不进入循环,但是这样线程真的中断了吗?只能说这个时候不进入(2)这个循环而已吧?其实run()这个方法应该还在运行中吧?也就是说这个线程没有真正意义上的中断。如果把(3)改成
while(true){
System.out.println("Thread exiting under request..."); //(4)
}那还会继续执行(4)的代码,对不对?不知道我的理解是否正确,请各位大吓指正!
解决方案 »
- 关于thread中的join方法的疑问,请高人指点下小弟,谢谢
- FTP 多线程 同步
- 求 thinkiing in java 第四版的答案飞!!
- 求一超难算法,高手请进!!!
- 关于int转byte的问题
- 面试题:用hibernate的session时要注意几点
- 请教 JDK1.4.2 的一个“规则表达式”的问题:过滤以"L_"开头的文件名
- jni中调用VC的DLL(关于字符串的操作)
- 如何用java读取类似这样的ini文件
- oracle8.16下的乱码?ZHS16GBK和java的字符转化都试过了,还有什么可能情况?
- httpclient 提交xml
- 请问jspa后缀的页面使用了什么技术或框架?
这时线程也就结束了
你可以这样看线程的状态。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) }}
还是没看出来
在(1)中,把stop置为true 了后,确实可以不进入循环,但是这样线程真的中断了吗?只能说这个时候不进入(2)这个循环而已吧?其实run()这个方法应该还在运行中吧?也就是说这个线程没有真正意义上的中断。
——————————————————————————————————————————
当sotp设置成true以后就跳出while循环了。。然后执行输出语句。。执行完后线程结束
如果把(3)改成
while(true){
System.out.println("Thread exiting under request..."); //(4)
}那还会继续执行(4)的代码,对不对?
——————————————————————————————————————
如果这样改线程就不会终止而是一直满足。。一直死循环了。。
“没有任何语言方面的需求要求一个被中断的线程应该终止。
中断一个线程只是为了引起该线程的注意 ,被中断线程可以决定如何应对中断。”这是core java2中的原话。