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

如何設(shè)置線程運(yùn)行的時(shí)間

前輩們好!問(wèn)題如下:

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

回答
編輯回答
九年囚

上面的代碼有些問(wèn)題,并沒(méi)能真正結(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,將會(huì)輸出"任務(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 有一個(gè)方法 timedJoin,如果線程未在指定時(shí)間運(yùn)行完,或者指定時(shí)間內(nèi)運(yùn)行結(jié)束,代碼會(huì)向下走,這時(shí)使用 isAlive 判斷是否執(zhí)行結(jié)束。

2017年2月8日 11:34