How to Create Java Thread Programming with New Runnable()
I'm very interested in Thread Programming. It will to be the parallel process, make all process done simultaneously in amount of times. It was also a hard coding and logic, because not another thread method can run smoothly.
After I learned Java, it became realized, especially after I knew a new method - Runnable(). Here is the example codes that implement the Thread and Runnable(). A Runnable() method will be posted and destroyed by an Handler(). Post method can be executed with a delay time.
In this codes, I use Android Studio with Java Programming. I created 2 threads that will execute 2 methods, display waiting timer (like stopwatch) and randomizing colors & numbers and then display it in Buttons.
I use join() function to make th2 will run after th1 executed completely. In this flow, th1 executes the reset procedure and th2 executes the counter process.
th1= new Thread(new Runnable() {@Override
public void run() {
bStopRun= true;
handlerShow.removeCallbacks(timerShowNumber, 0);
ResetBtn(btnChoices, 60, false);
}});
th1.start();
th2= new Thread(new Runnable() {
@Override
public void run() {
try {
th1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
bStopRun= false;
mHandler.post(new Runnable() {
@Override
public void run() {
StartTimeaAns = SystemClock.uptimeMillis();
handlerShow.postDelayed(timerShowNumber, 0);
}
});
...
};
th2.start();
public Runnable timerShowNumber = new Runnable(){
public void run(){
if(bStopRun && bStopRunTh1){
handlerShow.removeCallbacks(timerShowNumber);
ResetToWhite();
return;
}
MillisecondTimeAns = SystemClock.uptimeMillis() - StartTimeaAns;
...
}