Java Interrupt Related

In Java, the main process can have several threads at a time, but only a few of them can run concurrently, so it is needed to cancel some thread at times and do the other thread, through interrupt. Interrupt is realized through the InterruptedException, if the other thread interrupt the current running thread, and if the current running thread is running methods like sleep(), which is able to throw InterruptedException, then the method throws an InterruptedException for the try{}catch{InterruptedException e} part of the method. So if a thread is defined to be able to be interrupted, it must be designed so that it invokes methods able to throw InterruptedException periodically or using the following code at times:

1 //check if a thread is being trying to interrputed
2 if( Thread.interrupted() ){
3     throw new InterruptedException();
4 }

Note that invoking Thread.interrupt sets the flag Interrupt Status Flag, when Checks for an interrupt by invoking the static method Thread.interrupted, the ISF is reset. Using the non-static isInterrupted method, by one thread to query the interrupt status of another, does not change ISF. By convention, any method that exit by throwing an InterruptedException clears ISF when it does clear the status, however, the ISF might be set up again by another thread invoking interrupt.

Using Joins method to wait for the completion of another. t.join() usage causes the current running process to pause execution and wait till thread t terminates. It has several overloads allowing developer to specify its waiting period. As with sleep. join is dependent on OS for timing, so keep in mind that this method may not wait as long as you specify. The joins() method can also throw InterruptedException.

When Thread.start(), a new thread starts running together with the thread that started it. The accessible thread t stop running when the other thread calls t.interrupt(). This method invokes some certain method running in thread t to throw InterruptedException.

posted on 2016-04-15 13:46  三叁  阅读(160)  评论(0编辑  收藏  举报

导航