各位好
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了吗?
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,我想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.
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.