zoukankan      html  css  js  c++  java
  • Java终止线程

    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("线程已经退出!"); 
        }
        
    }
  • 相关阅读:
    SQLServer XML
    批量数据入库
    iBatis --> MyBatis
    一句话,一段文
    一首诗,一阕词
    Web Service
    一天一首现代诗
    一天一首歌
    DB2
    Kafka
  • 原文地址:https://www.cnblogs.com/mstk/p/5924035.html
Copyright © 2011-2022 走看看