設想這樣的情景
有的時候我們需要一種規范的思路
我們首先要明白
在Java的早期版本中
我們的正確思路是
首先要理解interrupt方法做了什麼
但是如果線程被阻塞了(sleep or wait)
同樣的
我們調用了interrupt並不意味著線程會終止
在本文中我們將會討論終止線程的規范用法
首先我們來看兩種情形的後台線程寫法
public void run() {
try{
…
while(!Thread
{
do more work
}
}
catch(InterruptedException)
{
//thread was interrupted during sleep or wait
}
finally
{
cleanup
}
//exiting the run method terminates the thread }
public void run() {
try{
…
while( more work to do)
{
do more work
Thread
}
}
catch(InterruptedException)
{
//thread was interrupted during sleep or wait
}
finally
{
cleanup
}
//exiting the run method terminates the thread }
第一種寫法適用於後台下載
第一種寫法利用了interrupt方法
事實上這兩種寫法的區別就在於第二種使用了sleep
在我們的使用示例中
這一段是實現文件拷貝的
private class CopyRunnable implements Runnable {
@Override
public void run() {
File fromFile = new File(Environment
long fileLength = fromFile
long copyedLength =
File toFile = new File(Environment
if (toFile
toFile
}
try {
FileInputStream fileInputStream = new FileInputStream(fromFile)
FileOutputStream fileOutputStream = new FileOutputStream(
toFile
byte[] buffer = new byte[
int readLength =
while (!Thread
&& (readLength = fileInputStream
fileOutputStream
copyedLength += readLength;
int progress = (int)
((float) copyedLength / fileLength *
handler
}
} catch (FileNotFoundException e) {
e
} catch (IOException e) {
e
} finally {
handler
}
}
}
這一段是實現矩形繪圖的
private class DrawRunnable implements Runnable {
@Override
public void run() {
try {
while (true) {
long beginTime = System
paint
getCoor()
postInvalidate()
long endTime = System
if (endTime
Thread
}
}
} catch (InterruptedException e) {
e
} finally {
}
}
}
實際上這兩種寫法都是利用了interrupt方法的特點
最後做一下方法總結
void interrupt()
向線程發送中斷請求
static boolean interrupted()
測試當前線程(即正在執行這一命令的線程)是否被中斷
boolean isInterrupted()
測試線程是否被中斷
static Thread currentThread()
返回代表當前執行線程的Thread對象
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27558.html