In my android program an Activity calls a new surface view class, which then in turn calls a new thread class. I want to be able to pass a value to the thread class from the activity’s onPause and onResume methods, so I can pause and resume the thread. The only way I know to pass this data is by creating a new instance, which would just create a different thread. How should I go about this without creating a new thread instance?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameSurface(this));
}
@Override
protected void onResume() {
super.onResume();
//Would like to pass this value
int state = 1;
}
@Override
protected void onPause() {
super.onPause();
//Would like to pass this value
int state = 2;
}
A little background on concurrency
Passing values in concurrency is the easy part. Look into the
AtomicIntegerdata type (More information here). Atomicity also meansAll or nothing. This data type isn’t necessarily sending data between threads or processors (like you would withmpi) but it is merely sharing data on its shared memory.But what is an Atomic Action?….
I highly recommend you read this, it covers everything from
atomicity,thread pools,deadlocksandthe "volatile" and "synchronized" keyword.Start Class This will execute a new thread (It can also be referred to as our
Main Thread).Because the integer is atomic, you can also retrieve it anywhere but the
main methodin the Start Class withSystem.out.println("[run start] current state is... "+state.intValue());. (If you wish to retrieve it from themain method, you will have to setup a Setter/Getter, like I’ve done so in the Action Class)Action Class This is our thread in action (It can also be referred to as our
Slave Thread).The Console Output
As you can see, the
AtomicInteger stateis being shared in the memory between our threadsrandp.Solution and Things to look for…
The only thing you have to watch when doing concurrency is
Race Conditions/Deadlocks/Livelocks. SomeRaceConditionsoccur becauseThreadsare created in random order (And most programmers think in the mind set of sequential order).I have the line
Thread.sleep(1000);so that myMain Threadgives the slave threadra little time to update thestate(before allowingpto run), due to the random order of threads.In the solution I’ve posted I make my
Main Thread(akaclass start) as my main communicator to keep track of theAtomic Integerfor my slaves to use (akaclass action). My main thread is alsoupdatingthememory bufferfor theAtomic Integeron my slaves (The update on the memory buffer occurs in the background of the application and is handled by theAtomicIntegerclass).