在我们的使用示例中,对应这两种方法的使用代码如下:
这一段是实现文件拷贝的:
private class CopyRunnable implements Runnable {
@Override
public void run() {
File fromFile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/abc.exe");
long fileLength = fromFile.length();
long copyedLength = 0;
File toFile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/abc_.exe");
if (toFile.exists()) {
toFile.delete();
}
try {
FileInputStream fileInputStream = new FileInputStream(fromFile);
FileOutputStream fileOutputStream = new FileOutputStream(
toFile, true);
byte[] buffer = new byte[2048];
int readLength = 0;
while (!Thread.currentThread()。isInterrupted()
&& (readLength = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, buffer.length);
copyedLength += readLength;
int progress = (int)
((float) copyedLength / fileLength * 100);
handler.obtainMessage(0, progress, 0)。sendToTarget();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
handler.obtainMessage(1)。sendToTarget();
}
}
}
这一段是实现矩形绘图的:
private class DrawRunnable implements Runnable {
@Override
public void run() {
try {
while (true) {
long beginTime = System.currentTimeMillis();
paint.setColor(getColor());
getCoor();
postInvalidate();
long endTime = System.currentTimeMillis();
if (endTime - beginTime < 150) {
Thread.sleep(150 - (endTime - beginTime));
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
}
实际上这两种写法都是利用了interrupt方法的特点,通过线程的中断置位或者异常抛出来跳出循环进而终结线程。如果对这段代码感兴趣,可以到文章最后下载代码。
最后做一下方法总结:
void interrupt()
向线程发送中断请求。线程的中断状态将被设置为true.如果目前该线程被一个sleep调用阻塞,那么,InterruptedException异常被抛出。
static boolean interrupted()
测试当前线程(即正在执行这一命令的线程)是否被中断,注意,这是一个静态方法。这一调用会产生副作用,它将当前线程的中断状态设置为false.
boolean isInterrupted()
测试线程是否被中断。不像静态的中断方法,这一调用不会改变线程的中断状态。
static Thread currentThread()
返回代表当前执行线程的Thread对象。
|