Reputation: 41
I've a program that basically has a matrix of cells(shared memory) and cars(observable threads). Before each movement each car asks for access to the next cell, and if the next is blocked it enters a synchronized block which calls wait(), and the thread goes to sleep. I was wondering if there was any way I could make the car do something while it's on wait(), and then when he gets notified he can keep on doing what he was doing before the wait.
Upvotes: 0
Views: 89
Reputation: 734
I've done something similar to what you describe, using Handler
s for 2-way thread communication.
child/worker/'car' thread does work, goes to sleep for a set period (~100ms), and when waking up checks a thread class member variable for state changes.
parent thread will send Handler
messages to the worker thread, and the worker thread receives the commands and sets member variable in worker thread class, to be detected next time the worker exits sleep.
Below are the links I've been reviewing to grasp how to use Handler
s and communicate between threads effectively:
threads - nice overview of handlers (withOUT looper). w/ code example: com.indy.testing.TestMain.java.MyThread.java
http://indyvision.net/2010/02/android-threads-tutorial-part-3/
threads - ok overview of handlers and loopers http://techtej.blogspot.com/2011/02/android-passing-data-between-main.html
threads w/ 2way comm. w/ code example: sample.thread.messaging.ThreadMessaging.java http://codinghard.wordpress.com/2009/05/16/android-thread-messaging/
Upvotes: 0
Reputation: 200296
You'll have to redesign: don't model cars with threads. Have a thread pool perform any needed tasks and have an asynchronous model with callback functions guide the behavior of cars. If a cell is blocked, the state of the car simply doesn't change and the thread pool can do something else. When the cell is freed, fire the appropriate callback, which will submit the update task to the pool.
Upvotes: 1