我的应用程序开头有一个 if 语句
if (ready.equals("yes")){
...
}
后来在我的代码中我有
ready="yes";
但是 if 语句从未被调用,为什么? 准备="is";从后台线程调用,这是为什么吗?
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();
最佳答案
如果我错了,请纠正我。如果您说您的代码如下所示:
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
祝你好运!
编辑:请务必将上面的每个代码 fragment 包装在 synchronized (waitOnThis)
中。阻止,否则你会得到 IllegalMonitorStateException
.
关于java - Android 字符串 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30971671/