先上結論:
當一個線程調用wait後,未被喚醒前,調用interrupt方法,會拋異常InterruptedException,同時釋放對象鎖,線程終止。
/**
* test InterruptedException
*/
private void threadTest8() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (object) {
try {
Log.i(TAG, "run: 子線程開始執行,下面就調object.wait()了~");
object.wait();
Log.i(TAG, "run: 子線程開始執行完了~");
} catch (InterruptedException e) {
Log.i(TAG, "run: 子線程拋InterruptedException啦~");
Log.i(TAG, "threadTest8: 子線程 isInterrupted = " + Thread.currentThread().isInterrupted());
}
}
}
});
thread.start();
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "threadTest8: 在主線程調用 thread.interrupt()啦~");
thread.interrupt();
boolean isInterrupted = thread.isInterrupted();
Log.i(TAG, "threadTest8: 子線程 isInterrupted = " + isInterrupted);
}
結果如下:
07-16 21:48:16.259 19822-20962/com.hfy.demo00 I/MainActivityhfy: run: 子線程開始執行,下面就調object.wait()了~
07-16 21:48:17.258 19822-19822/com.hfy.demo00 I/MainActivityhfy: threadTest8: 在主線程調用 thread.interrupt()啦~
07-16 21:48:17.259 19822-19822/com.hfy.demo00 I/MainActivityhfy: threadTest8: 子線程 isInterrupted = true
07-16 21:48:17.260 19822-20962/com.hfy.demo00 I/MainActivityhfy: run: 子線程拋InterruptedException啦~
07-16 21:48:17.261 19822-20962/com.hfy.demo00 I/MainActivityhfy: threadTest8: 子線程 isInterrupted = false -中斷標誌位復位
另外,中斷線程還可以:
/**
* 中斷 線程
*/
private void threadTest9() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (object) {
Log.i(TAG, "run: 子線程開始執行~");
//如果中斷,就結束。 另外,如果此處是while(true),那麼即使主線程調了中斷,還是會一直走。
while(!Thread.currentThread().isInterrupted())
{
Log.i(TAG, "run: 子線程執行中~");
}
Log.i(TAG, "run: 子線程執行完了~");
}
}
});
thread.start();
try {
TimeUnit.MILLISECONDS.sleep(5);//這裏是讓子線程先執行,然後再中斷
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "threadTest8: 在主線程調用 thread.interrupt()啦~");
thread.interrupt();
boolean isInterrupted = thread.isInterrupted();
Log.i(TAG, "threadTest8: 子線程 isInterrupted = " + isInterrupted);
}
結果:
07-16 22:24:30.479 24596-24972/com.hfy.demo00 I/MainActivityhfy: run: 子線程開始執行~
run: 子線程執行中~
07-16 22:24:30.483 24596-24972/com.hfy.demo00 I/MainActivityhfy: run: 子線程執行中~
07-16 22:24:30.483 24596-24596/com.hfy.demo00 I/MainActivityhfy: threadTest8: 在主線程調用 thread.interrupt()啦~
07-16 22:24:30.483 24596-24972/com.hfy.demo00 I/MainActivityhfy: run: 子線程執行中~
07-16 22:24:30.483 24596-24972/com.hfy.demo00 I/MainActivityhfy: run: 子線程執行中~
run: 子線程執行完了~
07-16 22:24:30.483 24596-24596/com.hfy.demo00 I/MainActivityhfy: threadTest8: 子線程 isInterrupted = true