Multithreading in Java with example

 

Multithreading in Java

Multithreading in Java

 When we want to run multiple programs or tasks simultaneously is known as multitasking. For example running VLC, Word, and Browser at a given time is an example of multitasking. Every program in memory is known as a process and each process has taken a single unit of time.

 The multitasking can be achieved by

  • Multiprocessing which is based on process and associated with operating system level.
  • Multitasking is based on thread and it is associated with programmer.

 
Multitasking

What is Thread in java?

A thread is a subpart of a process which lightweight and it is the smallest sequence of a program or a process. Each thread has some priority and the higher the priority higher the chances of executing preference.

The life cycle of thread

The JVM controlled the life cycle of a thread and it has five states 1. New, 2. Runnable, 3. Running, 4. Non-Runnable (Blocked) and last 5. Terminated.

How to create a thread in java?

We can thread in java by two method

First, With Thread class extending and second with implementing Runnable interface.

Java provides predefine API to implement thread, a few of commonly used API as follows

  • thread () Create a new thread
  • Thread (Runnable target)
  • Thread (String name)
  • Thread (Runnable target, String name)
  • Thread (ThreadGroup g, Runnable target)

To create a thread we used two way first by extending Thread class and second by implementing Runnable interface and this done by overriding the run() method. After then start() is called.


By implementing Runnable interface

public class RunnableInteface implements Runnable

{ 

    public void run()

    { 

        System.out.println("thread is running.. by Runnable interface"); 

    } 

    public static void main(String args[])

    { 

        RunnableInteface ob=new RunnableInteface(); 

        Thread t1 =new Thread(ob); 

        t1.start(); 

    } 

}

Output

thread is running.. by Runnable interface

In the above program, we implement a Runnable interface. And override the run() method and then create an object of the class and that object passed in the Thread class constructor as Thread(ob).


By extending class Thread

public class ExtendingThread extends Thread

{ 

    public void run()

    { 

        System.out.println("thread is running..by extending class Thread."); 

    } 

    public static void main(String args[])

    { 

        ExtendingThread t1=new ExtendingThread(); 

        t1.start(); 

    } 

} 

Output

thread is running..by extending class Thread.


Another example

public class DemoThread extends Thread

{

    public void run()

    {

        for(int i=0; i<5; i++)

        {

            System.out.println(getName() + "i=" + i);

        }

    }

    DemoThread() // constructor

    {

        start();

    }  

    public static void main(String args[])

    {

        DemoThread ob1 = new DemoThread();

        DemoThread ob2 = new DemoThread();

    }

}

In the above program run() method override and invoked by its constructor method, a loop is run from 0 to 4 and print the thread name with the help of getThread() method. In main() method two objects are created. It will print the following output

Thread-1 i=0

Thread-1 i=1

Thread-1 i=2

Thread-1 i=3

Thread-1 i=4

Thread-0 i=0

Thread-0 i=1

Thread-0 i=2

Thread-0 i=3

Thread-0 i=4


Difference between Daemon and User Threads


The main difference between Daemon and User threads is, a Daemon thread is low priority thread and User thread is a high priority thread.

Daemon thread is used in the background supporting task and User thread is used in the foreground.

Daemon thread life depends on the User thread whereas User Thread are independent.

 

Creating of Daemon Thread

public class Daemon extends Thread {

 

    @Override

    public void run()

    {

        System.out.println("User Thread or Non-Daemon Thread");

    }

}

class DaemonThread

{

    public static void main(String[] args)

    { 

        Daemon daemon = new Daemon();

        daemon.start(); 

        System.out.println("Main Thread"); 

        System.out.println("Is " + daemon.getName() + " a Daemon Thread: " + daemon.isDaemon()); 

        System.out.println("Is " + Thread.currentThread().getName() + " a Daemon Thread: "

        + Thread.currentThread().isDaemon());

    }

}

Inter-Thread communication

When a process communicates with synchronized threads is known as inter-thread communication. It is used to check thread pooling in java. This can be achieved by notify(), notifyAll() and wait() method.


Few points about the thread

  • A thread is the smallest unit of execution
  • Multiple tasks execution is multitasking from the user perspective and from multithreading from an operating system perspective
  • Thread is lightweight
  • Thread is a part of the process and it is an instance of a program
  • Java thread can be created either by class Thread or by interface Runnable
  • in a thread a run() method override
  • The start() method automatically invoke the run() method
  • The yield method of thread provides a chance to wait for another thread
  • join() method is used to wait till the thread finishes its execution
  • sleep() method is used to delay in execution
  • Suspending a thread can be resume again later on by resuming it
  • stop() method stop the thread and make it dead, it can not be resume again
  • synchronized can be used to synchronize the thread

More Java programs 



SHARE THIS
Previous Post
Next Post