首先,对于不太具描述性的标题感到抱歉。
我有以下代码,它无法正常工作(或者我想要的)。
即使我打电话给“取消()”,时间继续......
private boolean cancelled;
private synchronized Bitmap renderBitmap(PatchInputStream pis){
File file = new File(Environment.getExternalStorageDirectory()+url);
FileOutputStream fos=new FileOutputStream(file);
byte buf[]=new byte[2000];
int len;
while((len=pis.read(buf))>0 && !isCancelled() ){
fos.write(buf,0,len);
}
fos.close();
if (isCancelled()){
cancelled=false;
return null;
}
Bitmap bm = saveBitmapToFile(file);
return bm;
}
public boolean isCancelled(){
return cancelled;
}
public void Cancel(){
cancelled=true;
}
这段代码有什么问题?我错过了什么吗?
答案 0 :(得分:2)
至少代码有一个并发错误,可以通过cancelled
volatile
来解决。否则,不保证其他线程看到新值。
(显然事实并非如此。)
另一种可能性是不调用cancel()方法。 (显然事实并非如此。)
还有一种可能性是在不同的对象实例上调用cancel()方法。尝试将System.out.println(System.identityHashCode(this))
添加到cancel()方法和while循环中,看看它们是否打印相同的值。
答案 1 :(得分:0)
根据@mibollma的建议,对取消的实例变量使用volatile
。这将确保没有Thread使用变量的缓存版本。如果这不起作用,您可以尝试以下建议:
您的cancel()
方法可能未被调用,带有while循环的Thread不允许它。使用Thread.yield()
方法。
使当前正在执行的线程对象暂时暂停并允许其他线程执行。
在你的while循环中:
while((len=pis.read(buf))>0 && !isCancelled() ){
fos.write(buf,0,len);
Thread.yield();
}