Multithreading in java with examples

by Chaitanya Singh

in Multithreading

  • A multithreaded program contains two or more parts that can run concurrently. Each part of such a program called a thread. Each thread has a separate path of its execution. So this way a single program can perform two or more tasks simultaneously.
  • Threads are lightweight processes; they share the same address space. Multithreaded programs make maximum use of CPU because idle time can be kept to minimum.
  • Handling of multithreading in java is quite simple.
  • Thread exists in several states. It can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended. A suspended thread can be resumed. A thread can be blocked when waiting for a resource. At any time a thread can be terminated.

Recommended Reads:

  1. Java threads
  2. Thread life cycle in Java

1.  The Thread class and Runnable Interface

  • Thread class and Runnable interface are used to create the thread in java.
  • To create a new thread in the class that wish to create the thread, it will either extend Thread class or implement the interface Runnable.
  • Following are the methods that help mange the thread.
    • getName: Obtain a thread’s name
    • getPriority: Obtain a thread’s priority
    • isAlive: Determine if a thread is still running
    • join: Wait for a thread to terminate
    • run: Entry point for the thread
    • sleep: suspend a thread for a period of time
    • start: start a thread by calling its run method

2.  Implementing Runnable

  • One way of creating a thread is to create a class that implements the Runnable interface and we need to only implement the run() method.
  • Inside the run method code for the job to be done by thread will be there.
  • This run method is the entry point for the thread and thread will continue till the time run method is finished.
  • After we create a class that implements Runnable we will instantiate an object of the type Thread from within that class by passing an object of the class that has implemented Runnable.
  • Once the thread is created it will start running when start() method is called on it. Basically start() method calls run().
  • See the following example, we have yet not discussed about isAlive() we will see the same in the sections ahead

[code language="java"]

<code>class Count implements Runnable
{
Thread thred ;
Count()
{
thred = new Thread(this, "my runnable thread");
System.out.println("my thread created" + thred);
thred.start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("My thread's run is over" );
}
}
class RunnableExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.thred.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over" );
}
}[/code]

3.  Extending Thread

  • Other way to create a thread is to create a new class that extends the Thread class.
  • Then to create an instance of that class.
  • Extending class should override the run() method which is the entry point for the new thread as described above.
  • Call start() method so that thread starts running.
  • See the following example, we have yet not discussed about isAlive() we will see the same in the sections ahead

[code language="java"]

<code>class Count extends Thread
{
Count()
{
super("my extending thread");
System.out.println("my thread created" + this);
start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("My thread's run is over" );
}
}
class ExtendingExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over" );
}
}[/code]

4.  Thread priorities

  • Thread priorities are the integers which decide how one thread should be treated with respect to the others.
  • Thread priority decides when to switch from one running thread to another, process is called context switching
  • A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU.
  • A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.
  • To set the priority of the thread setPriority() method is used which is a member of the class Thread.
  • When setting the priority it’s level is set which can be MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.

5.  About isAlive() and join()

  • In all the practical situations main thread should finish last else other threads which have spawned from the main thread will also finish.
  • To know whether the thread has finished we can call isAlive() on the thread which returns true if the thread is not finished.
  • Another method to achieve this is join(), this method when called from the parent thread makes parent thread wait till the time child thread terminates.
  • These methods are defined in the Thread class. Please refer the JAVA API to see the details.
  • Now you can understand the part in the above examples about isAlive().

6.  Synchronization

  • Multithreading introduces asynchronous behavior to the programs. If a thread is writing some data another thread may be reading the same data at that time. This may bring inconsistency.
  • When two or more threads need access to a shared resource there should be some way that the resource will be used only by one resource at a time. The process to achieve this is called synchronization.
  • To implement the synchronous behavior java has synchronous method. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object. All the other threads then wait until the first thread come out of the synchronized block.
  • When we want to synchronize access to objects of a class which was not designed for the multithreaded access and the code of the method which needs to be accessed synchronously is not available with us, in this case we cannot add the synchronized to the appropriate methods. In java we have the solution for this, put the calls to the methods (which needs to be synchronized) defined by this class inside a synchronized block in following manner.

Synchronized(object)
{
// statement to be synchronized
}

7.  Interthread Communication

  • We got few methods through which java threads can communicate with each other.
  • wait(), notify(), notifyAll().
  • All these methods can only be called from within a synchronized method.
  • To understand synchronization java has the funda of monitor. Monitor can be thought of as a box which can hold only one thread. Once a thread enters the monitor all the other threads have to wait until that thread exits the monitor.
  • wait()  tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
  • notify() wakes up the first thread that called wait() on the same object.
  • notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

8.  References

  • The Complete Reference Java 2 by Herbert Schildt

Target keywords: Multithreading in java, multithreading example in java,  programs that use multithreading,  java concurrency tutorial

Related Guides:

  1. Java OOPs concepts
  2. Java Constructors
  3. Java Polymorphism

{ 0 comments… add one now }

Leave a Comment

Our Friend's website link : FromDev.com