java 關閉線程

來源:互聯網
上載者:User

標籤:lock   stack   自動   ack   rri   read   class   rup   code   

public class ThreadService {    private Thread executeThread;    private boolean finished = false;    public void execute(Runnable task) {        executeThread = new Thread() {            @Override            public void run() {                Thread runner = new Thread(task);                runner.setDaemon(true);                runner.start();                try {                    runner.join();                    finished = true;                } catch (InterruptedException e) {                    System.out.println("intrupted   finished");                    //  e.printStackTrace();                }            }        };        executeThread.start();    }    public void shutdown(long mills) {        long currentTime = System.currentTimeMillis();        while (!finished) {            long cost=(System.currentTimeMillis() - currentTime);            System.out.println(cost);            if (cost>= mills) {                System.out.println("timeout!!!");                executeThread.interrupt();                break;            }            try {                executeThread.sleep(1);            } catch (InterruptedException e) {                System.out.println("execute is intrupeted");                break;            }        }        finished=false;    }}

通過關閉主線程的方式讓守護線程 自動關閉

子線程再運行結束時通過join 通知主線程  說自己執行完了,通過結束中斷主線程來讓子線程自動結束,解決了 線程block   中無法結束的問題

public class ThreadCloseForce {    public static void main(String[] args) {        ThreadService service=new ThreadService();        long start=System.currentTimeMillis();        service.execute(()->{            //read data            try {                Thread.sleep(2000);            } catch (InterruptedException e) {                e.printStackTrace();            }        });        service.shutdown(10000);        long end=System.currentTimeMillis();        System.out.println(end-start);    }}

 

java 關閉線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.