在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  Linux  HTML/ 如何設(shè)置線程運行的時間

如何設(shè)置線程運行的時間

前輩們好!問題如下:

有一個線程,給他規(guī)定執(zhí)行用時最大時間,如果他執(zhí)行的時間超過最大時間,就結(jié)束這個線程,代碼該怎么寫呢,
前輩們給指導指導,謝謝啦

回答
編輯回答
九年囚

上面的代碼有些問題,并沒能真正結(jié)束線程。稍微改下就可以了

Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread());
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                **return;**
            }
            System.out.println("任務(wù)繼續(xù)執(zhí)行..........");
        }
    });
    
    System.out.println(Thread.currentThread());
    thread.start();
    TimeUnit.SECONDS.timedJoin(thread, 3);
    
    if (thread.isAlive()) {
        thread.interrupt();
        throw new TimeoutException("Thread did not finish within timeout");
    }

如果,不加return,將會輸出"任務(wù)繼續(xù)執(zhí)行.........."

2018年9月12日 22:06
編輯回答
青瓷
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread());
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    
    System.out.println(Thread.currentThread());
    thread.start();
    TimeUnit.SECONDS.timedJoin(thread, 3);
    
    if (thread.isAlive()) {
        thread.interrupt();
        throw new TimeoutException("Thread did not finish within timeout");
    }

TimeUnit 有一個方法 timedJoin,如果線程未在指定時間運行完,或者指定時間內(nèi)運行結(jié)束,代碼會向下走,這時使用 isAlive 判斷是否執(zhí)行結(jié)束。

2017年2月8日 11:34