Interrupt notes

static void main public (String [] args) { 
the Thread the Thread new new T = (the Runnable new new () {
@Override
public void RUN () {
the try {
System.out.println ( "the begin SLEEP");
//Thread.interrupted ( ) clears the interrupt flag is false, System.out.println (Thread.interrupted ());
// If you call interrupt threads blocked on yet () will give the thread interrupt flag is set to true, then the call to throw immediately InterruptedException thrown when a blocking method.
                    Thread.sleep(2000);
System.out.println("after throwing...");
} catch (InterruptedException e) {
System.out.println("after catching...");
}
System.out.println("exit run()...");
}
});
t.start();
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t.interrupt() go");
t.interrupt();
System.out.println("t.interrupt() end");
}

结果:

1:begin sleep
2:t.interrupt() go
3:t.interrupt() end
4:after catching...
5:exit run()...

Because it is two threads, 3,4,5 random order

 

  The above is interrupted sleep, the next interrupt wait

  

  

static void main public (String [] args) { 
the Thread the Thread new new T = (the Runnable new new () {
@Override
public void RUN () {
the try {
System.out.println ( "the begin SLEEP");
            // the wait () method when the block must be in sync or synchronization method, and lock objects and call the object to be consistent, otherwise it will throw a runtime exception java.lang.IllegalMonitorStateException
                    synchronized (Thread.currentThread()){
Thread.currentThread().wait();
}
System.out.println("after throwing...");
} catch (InterruptedException e) {
System.out.println("after catching...");
}
System.out.println("exit run()...");
}
});
t.start();
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t.interrupt() go");
t.interrupt();
System.out.println("t.interrupt() end");
}

  结果:

1:begin wait
2:t.interrupt() go
3:t.interrupt() end
4:after catching...
5:exit run()...

  Because it is two threads, 3,4,5 random order

  In addition interrup () method can not be interrupted IO blocking and blocking mutex lock, then there are two solutions

  1: Close competitive resources, such as: When IO blocked, closed blocking flow, or use nio, nio provide a more humane interrupt response, the blocked channel will automatically respond to interrupts.

  2: Use of ReentrantLock lockInterruptibly in () method to get the lock, then locks the mutex may correspond interrup () method.

Guess you like

Origin www.cnblogs.com/zou-rong/p/12544730.html