Android Thread Example with its description


Example

While launching an application firstly main thread is executed. This Main thread handles all the UI concept of application. If we want to run long the task in which we don't need the UI then we use thread for running that task in background.

Here is the example of Thread which describes blow:

new Thread(new Runnable() {
    public void run() {
        for(int i = 1; i < 5;i++) {  
            System.out.println(i);  
        }
    }
}).start();

We can create thread by creating the object of Thread which have Thread.run() method for running the thread.Here, run() method is called by the start() method.

We can also run the the multiple threads independently, which is known as MultiThreading. This thread also have the functionality of sleep by which the currently executing thread to sleep (temporarily cease execution) for the specified number of time. But sleep throws the InterruptedException So, we have to handle it by using try/catch like this.

try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}