首页 > 移动平台 > 详细

Android立刻终止一个线程

时间:2017-02-09 13:29:27      阅读:262      评论:0      收藏:0      [点我收藏+]
/**
 * Created by JuTao on 2017/2/4.
 * 如何中止一个线程
 */
public class ThreadDone {
  public static void main(String[] args) throws InterruptedException {
    MyRunnable myRunnable=new MyRunnable();
    Thread thread = new Thread(myRunnable);
    thread.start();
    Thread.sleep(1000);
    //仅仅利用flag并不能使线程立刻中止,当run方法中有耗时操作时会等待执行完成才结束
    myRunnable.flag=false;
    thread.interrupt();
  }

  private static class MyRunnable implements Runnable {

    //立刻同步到子线程中
    private volatile boolean flag = true;

    @Override public void run() {
      while (flag&&!Thread.interrupted()) {
        System.out.println("running");
        try {
          Thread.sleep(8000);
        } catch (InterruptedException e) {
          //e.printStackTrace();
          //thread.interrupt()执行后会立刻进入catch
          return;
        }
      }
    }
  }
}

Android立刻终止一个线程

原文:http://www.cnblogs.com/wangfeng520/p/6381627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!