如何设置线程运行的时间

前辈们好!问题如下:

有一个线程,给他规定执行用时最大时间,如果他执行的时间超过最大时间,就结束这个线程,代码该怎么写呢,
前辈们给指导指导,谢谢啦

阅读 12.3k
2 个回答
    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,如果线程未在指定时间运行完,或者指定时间内运行结束,代码会向下走,这时使用 isAlive 判断是否执行结束。

上面的代码有些问题,并没能真正结束线程。稍微改下就可以了

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("任务继续执行..........");
        }
    });
    
    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,将会输出"任务继续执行.........."

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题