My function has to return data just after my thread end, I am using the wait() method after start() my thread but it doesn’t work :
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) {
// ...
}
}
in LogCat :
: 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.
What I’m doing wrong?
You’re looking for
join, notwait:waithas a different purpose, which is to signal another thread that an event has occurred. It requires a matching call tonotify. Furthermore, you need to acquire the lock on the object which is being used towait/notify, which is why you are getting that exception.And another thing: starting a thread and then immediately joining it is redundant. You might as well execute everything on the main thread.