I am new to android programming.Sorry if this type of question have been asked before.
I am getting trouble while creating threads.In my code, I have initialized int i=500; and in my first thread t1, i want to increment the value of t1 if(i<5000) and also on my thread t2 want to check the condition where the value of t2 is decremented if(i>0)
Please help...Thanks in advance
Here is the plain java Thread implementation for android as you required for this specific increment/decrement problem...
// class lass level declarations
private static int DEF_VALUE = 500;
private static int MIN_VALUE = 0;
private static int MAX_VALUE = 1000;
private AtomicInteger i = new AtomicInteger(DEF_VALUE);
private Thread t1 = null;
private Thread t2 = null;
private void initThreads() {
Log.i(TAG, "Initializing Threads...");
t1 = new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "Starting T1.");
while (i.get() < MAX_VALUE) {
i.incrementAndGet();
Log.d(TAG, String.format("Incremented by T1, i = %d", i.get()));
}
Log.i(TAG, "Finishing T1.");
}
});
t2 = new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "Starting T1.");
while (i.get() > MIN_VALUE) {
i.decrementAndGet();
Log.d(TAG, String.format("Decremented by T2, i = %d", i.get()));
}
Log.i(TAG, "Finishing T2.");
}
});
t1.start();
t2.start();
}
Hope this helps...:)
Update: Source updated to use AtomicInteger instead of plain int to avoid concurrent access issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With