zoukankan      html  css  js  c++  java
  • 关于java 线程的停止同时用 interrupt 和 join 的作用

     

    /**

     * @FileName: ThreadTest.java

     * @Description:

     * @Author : xingchong

     * @CreateTime: Sep 22, 2018 12:01:01 PM

     * @Copyright: 超火影游 Copyright (c) 2017

     * @Version: 1.0

     */

    public class ThreadTest implements Runnable {

     

    private boolean stop = false;

     

    private Thread thread;

     

    private int flag;

     

    public ThreadTest(){

    this.thread = new Thread(this, ThreadTest.class.getSimpleName());

    this.flag = 0;

    }

     

    private String getName(){

    return "["+Thread.currentThread().getName()+"] ";

    }

     

    /*

    * (non-Javadoc)

    * 

    * @see java.lang.Runnable#run()

    */

    @Override

    public void run() {

    while(!stop){

    System.out.println(this.getName() +", i am running..."+ this.flag++);

    if(this.flag > 30){

    break;

    }

    try {

    Thread.sleep(2000);

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    }

    System.out.println(this.getName()+", i am end...");

    }

     

    public synchronized void start(){

    this.thread.start();

    }

     

    public synchronized void stop(){

    System.out.println(this.getName() +", stop the thread...");

    this.stop = true;

    this.thread.interrupt();//马上中断 thread 正在进行的 sleep 等操作,而让停止操作立即执行

    //若没有上面interrupt()方法,会导致 thread 发呆在 sleep ,担耽时机

     

    try {

    this.thread.join();//为了现在马上转入 thread 线程,以触发this.stop引起的停止操作,而不用再让main线程抢 CPU,担耽时机

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

     

    //若没有上面的 join()方法,会导致以下代码在停止前执行

    for (int i = 0; i < 3; i++) {

    System.out.println(this.getName() +"in stop ...");

    }

    }

     

    public static void main(String[] args) {

    ThreadTest threadTest = new ThreadTest();

    threadTest.start();

     

    for (int i = 0; i < 3; i++) {

    System.out.println(threadTest.getName()+", main...." + i);

    try {

    Thread.sleep(2000);

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    }

     

    threadTest.stop();

    System.out.println(threadTest.getName()+", main is end...");

    }

     

    }

  • 相关阅读:
    Android开发学习之路-使用Handler和Message更新UI
    Android开发学习之路-Service和Activity的通信
    Android开发学习之路-自定义ListView(继承BaseAdapter)
    URI、URL、URN
    理解 node.js 的事件循环
    创建hexo风格的markdown页面
    heroku
    js通过沿着作用域链还是原型链查找变量
    浏览器中实现3D全景浏览
    数据可视化图表ECharts
  • 原文地址:https://www.cnblogs.com/xingchong/p/9689964.html
Copyright © 2011-2022 走看看