Java 可中断线程
http://blog.csdn.net/sapphiron/article/details/3018053
?
PART.1?无法中断的线程
一个无法中断的线程的例子。
方法
超时后的处理
ReentrantLock
ReadLock
WriteLock
tryLock(long, TimeUnit)
返回false
Condition
await(long, TimeUnit)
awaitNanos(long)
awaitUntil(Date)
返回false
Future
get(long, TimeUnit)
TimeoutException
CyclicBarrier
await(long, TimeUnit)
TimeoutException
CountDownLatch
await(long, TimeUnit)
返回false
Exchanger
exchange(V, long, TimeUnit)
TimeoutException
Semaphore
tryAcquire(long, TimeUnit)
返回false
BlockingQueue<E>
offer(E, long, TimeUnit)
poll(long, TimeUnit)
返回false
返回null
BlockingDeque<E>
offerFirst(E, long, TimeUnit)
offerLast(E, long, TimeUnit)
poolFirst(long, TimeUnit)
poolLast(long, TimeUnit)
返回false
?
返回null
ServerSocket
accept()
通过setSoTimeout设置超时时间。
SocketTimeoutException
该方法在阻塞时如果线程被中断,可以抛出一个异常:?
类
方法
异常
Thread
sleep(long)
join()
InterruptedException
?
ReentrantLock
ReadLock
WriteLock
lockInterruptibly()
InterruptedException
Condition
await()
InterruptedException
Future
get()
InterruptedException
CyclicBarrier
await()
InterruptedException
CountDownLatch
await()
InterruptedException
Exchanger
exchange(V)
InterruptedException
Semaphore
acquire()
InterruptedException
BlockingQueue<E>
put(E)
take()
InterruptedException
BlockingDeque<E>
putFirst(E)
putLast(E)
takeFirst(E)
takeLast(E)
InterruptedException
调用不可中断阻塞方法的可中断版本:?
类
阻塞方法
可中断方法
ReentrantLock
ReadLock
WriteLock
lock()
tryLock()
tryLock(long, TimeUnit)
lockInterruptibly()
Condition
awaitUninterruptibly()
await()
await(long, TimeUnit)
awaitNanos(long)
awaitUntil(Date)
Semaphore
acquireUninterruptibly()
acquire()
tryAcquire()
tryAcquire(long, TimeUnit)
不能设置超时也不能抛出异常的阻塞方法:PART.5?处理Thread.sleep()
1.?捕获异常并结束线程
捕获InterruptedException异常,开始清理操作并结束线程。Consumer:其中,TestData是一个简单的可序列化的类。见“PART.2可中断的线程”和“PART.4 处理阻塞”。