mstk

Thread提供了stop()方法终止线程,但是该方法是强行终止,容易产生一些错误,已经被废弃。

可以使用退出标志来终止线程,在run()函数里面设置while循环,把退出标志作为while的条件,当条件为false时,run函数执行完毕,线程就自动终止了。

package com.my_code.thread;

public class MyThread extends Thread {

    public volatile boolean isRunning = true; 
    
    public void run(){
        while (isRunning){
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    public void stopIt(){
        isRunning = false;
    }
    
    public static void main(String[] args) throws InterruptedException{
        MyThread thread = new MyThread();
        thread.start();
        sleep(10000);
        thread.stopIt();
        thread.join();
        System.out.println("线程已经退出!"); 
    }
    
}

分类:

技术点:

相关文章:

  • 2021-06-29
  • 2022-12-23
  • 2021-07-17
  • 2022-12-23
  • 2022-12-23
  • 2021-12-16
  • 2021-12-15
猜你喜欢
  • 2021-06-09
  • 2021-12-01
  • 2022-12-23
  • 2021-09-14
  • 2022-12-23
  • 2021-12-15
  • 2021-12-15
相关资源
相似解决方案