2016-11-05 112 views
1

当线程处于睡眠状态时,它仍然保存着对象的锁,当它中断时,它是否释放锁并进入就绪状态或将它继续执行而不改变状态?中断对象上的睡眠线程释放锁的异常

+0

睡眠状态不存在,你是指WAITING? –

+0

睡眠你是指'Thread.sleep(x)'或'obj.wait()'? –

+0

但是如果你调用* Thread.sleep()*为什么你应该继续锁定资源?也许你应该先释放,并尝试从睡眠恢复时重新获得锁定。无论如何,由于threadInterruption是一个异常,它取决于如何处理异常。我会期待一个最后的块来清理。 –

回答

2

当它被中断时,它是否释放锁并进入就绪状态 或者它会继续执行而不改变状态?

被中断的线程只是状态更改(已设置的标志)而不是状态更改,它对是否释放锁没有影响。

只有在相应的对象实例上调用wait(有或没有超时),或者它将从同步块退出,被中断或不会改变任何事情时,持有对象监视器的线程才会释放它规则。


下面是一个简单的代码,给出了这个概念:

// Used to make sure that thread t holds the lock before t2 
CountDownLatch latch = new CountDownLatch(1); 
Thread t = new Thread(
    () -> { 
     synchronized (someObject) { 
      // Release t2 
      latch.countDown(); 
      for (int i = 1; i <= 2; i++) { 
       try { 
        System.out.println("Sleeping " + i); 
        // Sleep 2 sec and keep holding the lock 
        Thread.sleep(2_000L); 
        System.out.println("Sleep over " + i); 
       } catch (InterruptedException e) { 
        System.out.println("Interrupted " + i); 
       } 
      } 
     } 
    } 
); 
Thread t2 = new Thread(
    () -> { 
     try { 
      // Wait to be release by t 
      latch.await(); 
     } catch (InterruptedException e) { 
      throw new IllegalStateException(e); 
     } 
     System.out.println("Trying to get in"); 
     synchronized (someObject) { 
      System.out.println("In"); 
     } 
    } 
); 
// Start the threads 
t.start(); 
t2.start(); 
// Waiting 1 sec (< 2 sec) only before interrupting t 
Thread.sleep(1_000L); 
// Interrupt t 
t.interrupt(); 

输出:

Trying to get in 
Sleeping 1 
Interrupted 1 
Sleeping 2 
Sleep over 2 
In 

正如你可以在输出线t2进入同步看到只有当线程t从同步中退出时才会阻塞(获取锁定) zed块。线程t已被中断的事实并未使其释放该锁。

+0

这足够清楚了吗? –