天天看点

java线程学习3——线程的停止

方法一 stop方法

thread t = new thread(new mythread());

t.stop();

非常不友好,该方法已经被废弃。使用该方法,线程直接停止,可能很多资源没有关闭,还有可能造成死锁。

方法二 interrupt方法

public class sleepthread implements runnable

{

 /**

  * 线程运行时执行的方法

  */

 public void run()

 {

  try

  {

   // 该线程进入阻塞状态5秒

   thread.sleep(5000);

   for (int i = 0; i < 500; i++)

   {

    system.out.println(thread.currentthread().getname() + i);

   }

  }

  catch (interruptedexception e)

   // 若调用该线程的interrupt方法,会报该异常,真实程序中可以关闭一些资源

   e.printstacktrace();

 }

}

package cn.xy.thread;

public class sleeptest

 public static void main(string[] args)

  sleepthread tr = new sleepthread();

  thread t = new thread(tr);

  t.start();

  for (int i = 0; i < 500; i++)

   system.out.println(thread.currentthread().getname() + i);

  t.interrupt();

若调用该线程的interrupt方法,会报interruptedexception异常,真实程序中可以捕捉该异常并关闭一些资源。

方法三 flag

public class stopthread implements runnable

 private boolean flag = true;

  while (flag)

   // flag变为false后可能会完成该线程的最后一次输出

   system.out.println(thread.currentthread().getname());

 public void shutdown()

  system.out.println("我被shutdown了!");

  flag = false;

public class stoptest

  stopthread st = new stopthread();

  thread t = new thread(st);

  for (int i = 0; i < 10; i++)

  system.out.println("主线程结束!");

  st.shutdown();

可以很灵活控制线程的结束,shutdown中可以关闭资源。