package com.Thread.Demo1;
import java.awt.*;
import javax.swing.*;
import java.util.concurrent.RunnableFuture;public class MyThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Aaa a1=new Aaa(10);
Thread a_t=new Thread(a1);
a_t.start();
}}class Aaa implements Runnable
{
int x;
public Aaa(int x)
{
this.x=x;
} @Override
public void run() 
{
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x--;
System.out.println("x="+x);
if(x<0)
{
break;
}

}

}

}问题是,这里break后,a_t.start()的线程是不是已经dead了?如果不是有什么办法可以让这个线程结束?
if(x<0)
{
break;
}

解决方案 »

  1.   

    问题是,这里break后,a_t.start()的线程是不是已经dead了? 是
    但一般是while(boolean)
    public void run() {
    boolean isDead = true;
    while (isDead) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    x--;
    System.out.println("x=" + x);
    if (x < 0) {
    isDead = false;
    } } }
      

  2.   

    如果break被执行,那么就会跳出while(true)循环,run函数执行完毕,线程就自然结束了。
      

  3.   

    执行了break语句,就跳出了while循环了,线程也就结束了。因为是先执行打印语句,所以-1要被打印出来。
      

  4.   

    输出的结果是
    x=9
    x=8
    x=7
    x=6
    x=5
    x=4
    x=3
    x=2
    x=1
    x=0
    x=-1
      

  5.   

    谢谢各位大神指导。基本上是懂了。帮助文档里边的stop(),是不是在后面的升级中已经得到了优化?
      

  6.   


    stop() 已经被废弃(Deprecated),不推荐使用;相关的还有suspend()、resume()。可以选用interrupt(),另外推荐的做法是可以自行编写停止方法。
    参考:
    Why is Thread.stop deprecated?Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.
      

  7.   


    还有一个问题,Thread dead以后,Thread.currentThread().getName() 看到的ID号是++的。java里边对这个ID有没有什么说明?每起一个Thread,ID都++,要是非常多了该怎么办,有没有释放的做法?
      

  8.   

    无所谓,Thread的Name可以自己设置,ID是int,要用完太难了。