如果代码该
thread线程中的代码执行结束就会关闭,但是如果该线程代码未执行完毕,即时主线程关闭,该线程也不会关闭
run方法内如果执行完,thread会自动关闭。
如果你在run方法内设定 while(true) ,则需要自己监控条件值,自行跳出循环。
package zhidao;
public class Test6 implements Runnable
{
int start = 0;
int times = 0;
Thread thread;
public Test6 ()
{
if (null == thread)
{
start ();
}
else
{
stop ();
}
}
public static void main ( String[] args )
{
new Test6 ();
}
public void start ()
{
if (null == thread)
{
thread = new Thread (this);
thread.setPriority (Thread.MIN_PRIORITY);
thread.setName (this.getClass ().getName ());
thread.start ();
}
}
public synchronized void stop ()
{
if (null != thread)
{
thread.interrupt ();
}
thread = null;
notifyAll ();
}
@Override
public void run ()
{
try
{
while (true)
{
if (times == 9)
{
stop ();
break;
}
start++;
if (start == 11)
{
times++;
start = times + 1;
}
System.out.print (start);
Thread.sleep (100);
}
}
catch (InterruptedException e)
{}
}
}
这个会自动关闭的