代码如下,此线程是为了接收文件的,我想再用户取消文件接收的时候,也同时停止掉该线程,该如何实现了~~~
private class WriteReceive implements Runnable {
private Socket receFileSocket; private ClientReceiveFile crf; private boolean stopFlag = false; public void setStopFlag(boolean stopFlag) {
System.out.println("stopFlag:"+stopFlag);
this.stopFlag = stopFlag;
} public WriteReceive(Socket receFileSocket, ClientReceiveFile crf) {
this.receFileSocket = receFileSocket;
this.crf = crf;
} public void run() {
if (crf.saveFileName != null) {
DataOutputStream dos = null;
try { int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int currentData;
long passedData = 0;
long currentFileSize = crf.fileSize; // System.err.println("in line 184 cfs init
// before"); dos = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(crf.savePath
+ crf.saveFileName)));
// cpp.timer.start();
if (receFileSocket != null) {
DataInputStream dis = new DataInputStream(
new BufferedInputStream(receFileSocket
.getInputStream()));
int read = 0;
while ((read = dis.read(buf)) != -1 && !stopFlag) {
passedData += read;
currentData = (int) (passedData * 100 / currentFileSize);
System.out.println("文件接收了" + currentData + "%\n");
crf.cpp.setPercentValue(currentData);
dos.write(buf, 0, read); }
dos.flush();
System.out.println("接收完成,文件存为" + crf.savePath + "\n"); receFileSocket.close();
} } catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
} } } }