Android的等待线程结束
问题描述:
我的函数只是我的线程结束后,我现在用的是wait()
方法start()
后返回的数据我的线程,但它不工作:Android的等待线程结束
private class getDataThread extends Thread {
@Override
public void run() {
super.run();
while (true) {
try {
// ...
Thread.sleep(100);
} catch (InterruptedException e) {
// ...
}
}
}
}
public void getSensorValues(Bundle bundle) {
// ...
getDataThread gdt = new getDataThread();
gdt.start();
try {
gdt.wait();
} catch (InterruptedException e) {
// ...
}
}
:
: An exception occurred during execution !
: Exception caught: java.lang.reflect.InvocationTargetException
: Exception cause: (SYSTEM) java.lang.IllegalMonitorStateException: object not locked by thread before wait() in getSensorValues
: status::FAILURE - output:: Possible errors: (SYSTEM) java.lang.IllegalMonitorStateException: object not locked by thread before wait() in getSensorValues.
我在做什么错?
答
您正在寻找join
,不wait
:
public void getSensorValues(Bundle bundle) {
// ...
getDataThread gdt = new getDataThread();
gdt.start();
try {
gdt.join();
} catch (InterruptedException e) {
// ...
}
}
wait
都有不同的目的,这是通知另一个线程已发生的事件。它需要与notify
相匹配的电话。此外,您需要获取对wait/notify
正在使用的对象的锁定,这就是您获得该例外的原因。
另一件事:启动一个线程,然后立即加入它是多余的。你不妨在主线程上执行一切。
答
wait()
不等待一个线程完成。它等待另一个线程呼叫notify()
或notifyAll()
。
相反,您需要使用join()
以便其他线程将加入当前线程。当前线程将阻塞,直到另一个线程结束。
也就是说,wait()
和notify()
需要位于正在使用的对象的块内。例如:
synchronized (lock) {
lock.wait();
}
http://*.com/questions/6020719/what-could-cause-java-lang-reflect-invocationtargetexception – 2012-07-13 10:17:15