/*
java 停止线程的方式
方法1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
当run方法执行完后,线程就会退出。但有时run方法是永远不会结束的。如在
服务端程序中使用线程进行监听客户端请求,或是其他的需要循环处理的任务。
在这种情况下,一般是将这些任务放在一个循环中,如while循环。如果想让循
环永远运行下去,可以使用while(true){……}来处理。但要想使while循环在某
一特定条件下退出,最直接的方法就是设一个boolean类型的标志,并通过设置这
个标志为true或false来控制while循环是否退出。下面给出了一个利用退出标志
终止线程的例子。
*/
class ThreadFlag implements Runnable
{
private boolean flag;
public void run()
{
while(!flag)
{
System.out.println(Thread.currentThread().getName() + "... run ..." +flag);
}
}
public void setFlag(boolean flag)
{
this.flag = flag;
System.out.println(this.flag);
}
}
class StopThreadDemo
{
public static void main(String[] args)
{
ThreadFlag thr_run = new ThreadFlag();
Thread thread = new Thread(thr_run);
thread.start();
try
{
Thread.sleep(300);
// thread.join();
}
catch (InterruptedException e)
{
}
thr_run.setFlag(true);
System.out.println("main thread exit");
}
}
/*
java 停止线程的方式
方法2: 使用interrupt方法终止线程
使用情况:当线程调用wait方法时,或者sleep很久,线程发生阻塞时,没有外界条件促使线程被唤醒,那么线程将会
一直保持阻塞状态,不会停止;
*/
class ThreadFlag implements Runnable
{
public synchronized void run()
{
while(!Thread.interrupted())
{
try
{
this.wait(); //注意前面要配合synchronized
// Thread.sleep(300);
// thread.join();
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + "... exception ..." +e);
break;
}
System.out.println(Thread.currentThread().getName() + "... run ..." );
}
}
}
class StopThreadDemo1
{
public static void main(String[] args)
{
ThreadFlag thr_run = new ThreadFlag();
Thread thread = new Thread(thr_run);
thread.start();
try
{
Thread.sleep(1000);
// thread.join();
}
catch (InterruptedException e)
{
}
/*
在调用interrupt方法后, wait方法抛出异常,然后输出错误信息:
Thread-0... exception ...java.lang.InterruptedException
*/
thread.interrupt();
/*
注意:在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个
是静态的方法interrupted(),一个是非静态的方法isInterrupted(),这两个
方法的区别是interrupted用来判断当前线是否被中断,而isInterrupted可以用来
判断其他线程是否被中断。因此,while (!isInterrupted())也可以换成
while (!Thread.interrupted())。 所以
thread.isInterrupted是判断thread线程,调用thread.interrupt()后thread.isInterrupted()为true
thread.interrupted是判断main线程,调用thread.interrupt()后thread.interrupted()为false
*/
// while(!thread.isInterrupted())
// {
// System.out.println(" thread not exception....." );
// thread.interrupt();
// }
// while(!thread.interrupted())
// {
// System.out.println(" thread not exception......." );
// thread.interrupt();
// }
System.out.println("main thread exit。。。");
}
}