我的应用程序开头有一个if语句
if (ready.equals("yes")){
...
}
以后我的代码
ready="yes";
但永远不会调用if语句,为什么? ready =“是”;是从后台线程调用的,这是为什么?
public void DownloadFromUrl(final String fileName) { //this is the downloader method
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL("https://xxxxxxx");
File file = new File(PATH + fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.e("Ready or not", ready);
ready="yes";
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
Log.e("Ready or not", ready);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
}).start();
答案 0 :(得分:1)
如果我错了,请纠正我。如果你说你的代码是这样的:
new Thread(new Runnable() { public void run()
{
// thread code
if (ready.equals("yes")) {
// handler code
}
// more thread code
}).start();
// later on...
ready = "yes";
并且您在ready = "yes"
之前询问为什么if (ready.equals("yes"))
没有执行,那是因为多个线程无法保证执行某个订单。如果您要在执行ready.equals("yes")
语句之前等到if
,那么您必须使用Object.wait()
和Object.notifyAll()
方法:
// this is a field
private Object waitOnThis = new Object();
new Thread(new Runnable() { public void run()
{
// thread code
waitOnThis.wait(); // blocks until notify / notifyAll is called on waitOnThis
// by this point ready.equals("yes")
if (ready.equals("yes")) {
// handler code
}
// more thread code
}).start();
// later on...
ready = "yes";
waitOnThis.notifyAll(); // unblocks threads waiting on waitOnThis
祝你好运!
编辑:请务必将上面的每个代码片段包装在synchronized (waitOnThis)
块中,否则您将获得IllegalMonitorStateException
。
答案 1 :(得分:0)
Application
' OnCreate
只会在创建应用时开始调用一次。
如果要通知下载已完成,请考虑使用回调。