一个关于线程的问题:线程停止以后,就会被回收吗?
各位好
Java code
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了吗?
------解决方案--------------------
对了 你怕被回收的话可以做个单列模式撒,
------解决方案--------------------
可以通过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.
------解决方案--------------------这种方式是比较好点,我也经常采用这种方式。线程中断也就停止了。