0

私の関数は、スレッドの終了直後にデータを返す必要があります。スレッドのwait()後にメソッドを使用しstart()ていますが、機能しません:

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) {
        // ...
    }
}

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.

私が間違っていることは何ですか?

4

2 に答える 2

4

You're looking for join, not wait:

public void getSensorValues(Bundle bundle) {
    // ...
    getDataThread gdt = new getDataThread();
    gdt.start();
    try {
        gdt.join();
    } catch (InterruptedException e) {
        // ...
    }
}

wait has a different purpose, which is to signal another thread that an event has occurred. It requires a matching call to notify. Furthermore, you need to acquire the lock on the object which is being used to wait/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.

于 2012-07-13T10:26:41.907 に答える
1

wait()スレッドが終了するのを待ちません。notify()別のスレッドがorを呼び出すのを待ちますnotifyAll()

join()代わりに、他のスレッドが現在のスレッドに参加するように使用する必要があります。現在のスレッドは、他のスレッドが終了するまでブロックされます。

つまり、 と の両方wait()が、使用されているオブジェクトのブロックnotify()内にある必要があります。synchronized例:

synchronized (lock) {
    lock.wait();
}
于 2012-07-13T10:16:58.363 に答える