Android立刻終止一個線程


/**
 * 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;
        }
      }
    }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM