考试报名信息,太谷教育信息网欢迎您!
当前位置:首页 > > 考试 > > 计算机类 > 内容页

利用Java终止线程的方法

2021-04-22 12:19:06计算机类访问手机版193

  利用Java终止线程的方法

  引导语:Java的主要工作是通过编程语言来制作互联网页面、制作动态效果以及网站等技术,以下是小编分享给大家的利用Java终止线程的方法,欢迎阅读!

  1、让线程的run方法执行完,线程自然结束。这种方法最好

  2、通过轮询和共享标志位的方法来结束线程,例如whileflag,flag的'初始值设为真,当需要结束时,将flag的值设为false。这种方法也不很好,因为如果whileflag方法阻塞了,则flag会失效

  public class SomeThread implements Runnable

  private volatile boolean stop = false;

  public void terminate

  stop = ture;

  public void run

  whilestop

  // ... some statements

  如果线程因为执行sleep或是wait而进入Not Runnable状态,假如是wait 用标志位就方法就不行了,

  public final void waitlong timeout

  throws InterruptedException

  此方法导致当前线程称之为 T将其自身放置在对象的等待集中,然后放弃此对象上的所有同步要求。即当前线程变为等待状态

  wait 的标准使用方法

  synchronizedobj

  while<不满足条件>

  obj.wait;

  满足条件的处理过程

  而您想要停止它,您可以使用第三种即

  3 使用interrupt,而程式会丢出InterruptedException例外,因而使得执行绪离开run方法,

  例如:

  public class SomeThread

  public static void mainString[] args

  Thread thread=new Threadnew Runnable

  public void run

  while !Thread.interrupted

  // 处理所要处理的工作

  try

  System.out.println"go to sleep";

  Thread.sleep1000;

  catch InterruptedException e

  e.printStackTrace;

  System.out.println"i am interrupted!";

  ;

  thread.start;

  thread.interrupt;

  执行结果为:

  go to sleep

  i am interrupted!