有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java线程中断:它会取消即将到来的wait()调用吗?

我有一个线程,它有一个传入的作业队列(包含作业描述的LinkedList)。当没有作业可处理时,线程在队列上用wait()阻塞。当外部作业调度程序对象在队列上放置新作业时,它会用notify()唤醒它

在程序关闭时,我调用线程上的interrupt()。当线程在wait()中等待作业时,会引发InterruptedException。我的问题是:如果我在线程不阻塞但执行某种工作时中断线程,那么会发生什么情况?已处理的项是队列中的最后一个(因此队列现在为空),并且在设置中断标志以便再次调用wait()之前,执行通过了isInterrupted()检查?它是否会抛出一个InterruptedException,因为中断标志已经设置,或者线程永远等待,因为新作业永远不会到达队列,并且没有人中断等待


共 (3) 个答案

  1. # 1 楼答案

    阅读^{}-

    Interrupts this thread.

    Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

    If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

    If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

    If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

    If none of the previous conditions hold then this thread's interrupt status will be set.

    Interrupting a thread that is not alive need not have any effect.

    因此,将要发生的只是设置线程的中断状态

    编辑

    如果阅读^{}的API规范,您将看到以下内容:

    Throws:

    InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

  2. # 2 楼答案

    虽然这是一个很老的问题,但我想补充一点,如果在lock.wait()期间调用Thread.currentThread().interrupt()方法(当线程处于WAITING状态时),这并不意味着线程将在内部立即抛出InterruptedException,第一个线程将进入BLOCKED状态(它将被另一个线程的lock.notify()/notifyAll()调用唤醒,这允许它竞争共享锁),中断标志设置为true,可能在一段时间后,只有在再次获得锁后(有时相当长的时间),它才能抛出^{(没有锁,它无法继续,甚至无法处理异常)

    package com.company;
    
    public class Main {
    
        public static void main(String[] args) {
            final Object lock = Main.class;
    
            // three simple threads
            Thread th1 = new Thread(() -> {
                synchronized (lock) {
                    for (int i = 0; i < 15; i++) {
                        sleepWithoutException(100);
                        System.out.println("th1 is doing some job!");
                    }
                }
            });
    
            Thread th2 = new Thread(() -> {
                synchronized (lock) {
                    for (int i = 0; i < 15; i++) {
                        sleepWithoutException(100);
                        System.out.println("th2 is doing some job!");
                    }
                }
            });
    
            Thread th3 = new Thread(() -> {
                synchronized (lock) {
                    for (int i = 0; i < 15; i++) {
                        sleepWithoutException(100);
                        System.out.println("th3 is doing some job!");
                    }
                }
            });
    
            // thread which will be in WAITING state after 1 second
            Thread th4 = new Thread(() -> {
                synchronized (lock) {
                    try {
                        sleepWithoutException(500);
                        lock.wait();
                        System.out.println("Continued");
                    } catch (InterruptedException e) {
                        System.out.println("interrupted! " + e);
                        System.exit(1);
                    }
                }
            });
    
    
            // execution
            th4.start();
    
            sleepWithoutException(100);
    
            th1.start();
            th2.start();
            th3.start();
    
            // thread which will monitor states of other threads
            new Thread(() -> {
                long start = System.currentTimeMillis();
                for (int i = 0; i < 1000_000; i++) {
                    sleepWithoutException(100);
                    System.out.println("                        -");
                    System.out.println("step: " + i + " , timeElapsed: " + (System.currentTimeMillis() - start));
                    if (i == 10) {
                        th4.interrupt();
                    }
                    System.out.println(
                            th1.getState() + " " + th1.isInterrupted() + "\n" +
                                    th2.getState() + " " + th2.isInterrupted() + "\n" +
                                    th3.getState() + " " + th3.isInterrupted() + "\n" +
                                    th4.getState() + " " + th4.isInterrupted()
                    );
                }
            }).start();
    
    
        }
    
        public static void sleepWithoutException(long time) {
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                System.out.println("fallen in sleep" + e);
            }
        }
    }
    

    请参阅下面的日志,因为您可以看到其他线程继续工作,而BLOCKING状态下带有标志isInterrupted的th4被设置为true(在调用Thread.currentThread().interrupt()方法之后)

                            -
    step: 0 , timeElapsed: 101
    BLOCKED false
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
                            -
    step: 1 , timeElapsed: 201
    BLOCKED false
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
                            -
    step: 2 , timeElapsed: 301
    BLOCKED false
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
                            -
    step: 3 , timeElapsed: 401
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING false
    th3 is doing some job!
                            -
    step: 4 , timeElapsed: 502
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING false
    th3 is doing some job!
                            -
    step: 5 , timeElapsed: 602
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING false
    th3 is doing some job!
                            -
    step: 6 , timeElapsed: 703
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING false
    th3 is doing some job!
                            -
    step: 7 , timeElapsed: 803
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING false
    th3 is doing some job!
                            -
    step: 8 , timeElapsed: 904
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING false
    th3 is doing some job!
                            -
    step: 9 , timeElapsed: 1004
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING false
    th3 is doing some job!
                            -
    step: 10 , timeElapsed: 1105
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    WAITING true
    th3 is doing some job!
                            -
    step: 11 , timeElapsed: 1205
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    BLOCKED true
    th3 is doing some job!
                            -
    step: 12 , timeElapsed: 1306
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    BLOCKED true
    th3 is doing some job!
                            -
    step: 13 , timeElapsed: 1406
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    BLOCKED true
    th3 is doing some job!
                            -
    step: 14 , timeElapsed: 1507
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    BLOCKED true
    th3 is doing some job!
                            -
    step: 15 , timeElapsed: 1607
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    BLOCKED true
    th3 is doing some job!
                            -
    step: 16 , timeElapsed: 1708
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    BLOCKED true
    th3 is doing some job!
                            -
    step: 17 , timeElapsed: 1808
    BLOCKED false
    BLOCKED false
    TIMED_WAITING false
    BLOCKED true
    th3 is doing some job!
                            -
    step: 18 , timeElapsed: 1909
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 19 , timeElapsed: 2009
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 20 , timeElapsed: 2110
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 21 , timeElapsed: 2211
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 22 , timeElapsed: 2311
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 23 , timeElapsed: 2412
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 24 , timeElapsed: 2512
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 25 , timeElapsed: 2613
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 26 , timeElapsed: 2713
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 27 , timeElapsed: 2814
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 28 , timeElapsed: 2914
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 29 , timeElapsed: 3015
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 30 , timeElapsed: 3115
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 31 , timeElapsed: 3216
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 32 , timeElapsed: 3316
    BLOCKED false
    TIMED_WAITING false
    TERMINATED false
    BLOCKED true
    th2 is doing some job!
                            -
    step: 33 , timeElapsed: 3417
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 34 , timeElapsed: 3517
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 35 , timeElapsed: 3618
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 36 , timeElapsed: 3718
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 37 , timeElapsed: 3819
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 38 , timeElapsed: 3919
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 39 , timeElapsed: 4019
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 40 , timeElapsed: 4120
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 41 , timeElapsed: 4220
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 42 , timeElapsed: 4321
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 43 , timeElapsed: 4421
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 44 , timeElapsed: 4522
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 45 , timeElapsed: 4622
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 46 , timeElapsed: 4723
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
                            -
    step: 47 , timeElapsed: 4823
    TIMED_WAITING false
    TERMINATED false
    TERMINATED false
    BLOCKED true
    th1 is doing some job!
    interrupted! java.lang.InterruptedException
    
    Process finished with exit code 1
    
  3. # 3 楼答案

    是的,被中断的线程在调用wait()时将抛出InterruptedException。这很容易自己测试

    public class TestInt {
        public static void main(String[] args) throws Exception
        {
            Thread.currentThread().interrupt();
    
            synchronized(TestInt.class) {
                TestInt.class.wait();
            }    
        }    
    }
    

    另外,请注意Object.wait()的javaodc:

    InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.