各位好
public class Testing
{
private static TestThread tester; class TestThread extends Thread
{
private int index = 0; private boolean running = true; @Override
public void run()
{
while (running)
{
System.out.println("" + ++index);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
} public void setRunning(boolean running)
{
this.running = running;
}
} public static void main(String[] args)
{
// 开启线程
tester = new TestThread();
tester.start(); // 消毁线程
tester.setRunning(false);
tester = null;
我想达到的效果是,使tester所指向的线程销毁掉,看网上说,直接调用stop()方法并不好,最好是在run()里自然地stop,所以设置了一个running变量。我想问的是,这个线程stop以后,就会被回收了,或是被destroy了吗?

解决方案 »

  1.   

     运行完了 就完了  ,你在start() 他又会运行,和其它类是一样一样的
      

  2.   

    可以通过Thread.getState()来看一下什么状态
    枚举类表示中总共有以下这些状态
    还有就像1楼说的可以重新start,我想run完后应该算是TERMINATED状态public static enum Thread.State
    extends Enum<Thread.State>A thread state. A thread can be in one of the following states:    NEW
        A thread that has not yet started is in this state.
        RUNNABLE
        A thread executing in the Java virtual machine is in this state.
        BLOCKED
        A thread that is blocked waiting for a monitor lock is in this state.
        WAITING
        A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
        TIMED_WAITING
        A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
        TERMINATED
        A thread that has exited is in this state.A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states. 
      

  3.   

    自己试了下,setRunning(false)之后线程的状态的确是TERMINATED了,而且调用start()方法是不行的,要调用run()方法才能再次执行,谢谢各位了。
      

  4.   

    嗯,对的,查了下,是不能再次调用start,直接调用run的话,相当于直接调用它的实例方法了,而不是新开一个线程。public void start()
    Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. 
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method). It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.