As mentioned before, in order to achieve a scalable application we need to create concurrent lines of execution to access the resources and calculate the results. Let say we want to download a file while the user has some interaction with the UI or we are trying to analyze data while we are publishing its real-time results to the user interface.
In order to achieve concurrency, Android SDK uses a subset of JAVA SDK, derived from the Apache Harmony project (although since Android 7 “Nougat” or API 24 it increasingly relies on OpenJDK libraries), gives developers access to low-level concurrency constructs such as java.lang.Thread
, java.lang.Runnable
, and the synchronized
and volatile
keywords.
The most basic one, java.lang.Thread
, is the class that is mostly used and is the construct that creates a new independent line of execution in a Java program:
public class MyThread extends Thread {
public void run() {
Log.d("MyThread ", "Hello concurrent world!");
}
}
We can run our thread using this line of code, Let say in a button click listener or anywhere else:
MyThread myThread = new MyThread();
myTread.start();
At this time, we will create an instance of our MyThread
, and when we start it in the second line, the system creates a thread inside the process and executes the run()
method.
We can give our thread a name(for debugging purposes ) or call the sleep method in our thread without interfering with the main UI thread. (Normally, if you call the sleep method in the main thread it hangs the UI)
public class MyThread extends Thread {
public void run() {
Thread.currentThread().setname("MyThread ")
Log.d("MyThread ", "First Message!");
Sleep(5000);
Log.d("MyThread ", "Seconde Message!");
}
}
And also, we can call Thread.join()
to block the current thread and wait for the other thread to finish or cancel.
There is another important class here, Runnable
interface, and this is how we use it:
public class MyRunnable implements Runnable {
public void run(){
Thread.currentThread().setname("MyRunnable!")
Log.d("MyRunnable", "Runnable Interface!");
// Do the work here
}
}
And same as the Thread class, we can run our runnable using these lines of the code:
Thread thread = new Thread(new MyRunnable());
thread.start();
It seems pretty easy, isn’t it? While starting new threads is easy, concurrency is actually a very difficult thing to do. Concurrent software faces many issues that fall into two broad categories: correctness (producing consistent and correct results) and liveness (making progress towards completion). In the following posts, we are going to investigate them and use some examples to describe them.
Stay tuned and don’t be a stranger! 😉