Multithreading in Java

What is Thread in Java

  • A thread is identified as the smallest unit of execution within a process, with multiple threads able to run independently while sharing resources.
  • Multitasking is defined as the ability of an operating system to run multiple processes at the same time.
multithreading in java

Multithreading in Java

  • Multithreading in java provides the fecility to executing multiple threads within a single process at the same time concurrently.
  • It utilizes CPU resources effectively, enhancing multitasking performance.

Multithreading has ability to perform more then one task at a time parallelly there are two types of multithreading

  • Process based Multitasking
  • Thread based Multitasking

Process based Multitasking –

While writing a java program in netbeans can we play songs in music player ? Yes , this is an example of process based multitasking.

For example: While using the browser , can we run the antivirus

Thread based Multitasking –

A thread is an execution path and so if a program has multiple execution paths , then we say that it is exhibiting thread based multitasking or multithreading .

For example: A thread is an execution path and so if a program has multiple execution paths , then we say that it is exhibiting thread based multitasking or multithreading .

Benefits of Multithreading

  • Utilization of of idle time of CPU
  • Makes the program Responsive
  • Resource sharing
how to achieve multithreading in java

How to Achieve Multithreading using Java

  • By Extending java.lang.Thread class
  • By Implementing an interface called java.lang.Runnable

What is “main Thread”


class Test {
    public static void main(String[] args) {
        System.out.println("Hello");
        int a = 10 / 0; // This will throw an ArithmeticException
        System.out.println(a);
        System.out.println("Bye!");
    }
}

class XYZ extends Thread {
    public void run() {
        Test.main(null);
    }
}

public class MainThreadExample {
    public static void main(String[] args) {
        XYZ mainThread = new XYZ();
        mainThread.start();
    }
}
implement multithreading in java

Basics of Thread Management

  • Java supports multithreading through its thread class and the Runnable interface, enabling developers to create concurrent applications.
  • Creating threads can be done by extending the Thread class or implementing the Runnable interface.

Thread Life Cycle and States

  • The lifecycle of a thread includes states such as New, Runnable, Blocked, Waiting, and Terminated.
  • Various methods, such as sleep and join, affect thread execution and management during their lifecycle.

Obtaining details about Main Thread


  public class ThreadExample {
      public static void main(String[] args) {
          Thread th = Thread.currentThread();
          System.out.println("Thread details: " + th);
          
          th.setName("Ravi");
          System.out.println("After name change: " + th);
          
          try {
              for (int i = 0; i < 5; i++) {
                  System.out.println(i);
                  Thread.sleep(1000);
              }
          } catch (InterruptedException ex) {
              System.out.println(th.getName() + " interrupted");
          }
      }
  }

A thread is an execution path and so if a program has multiple execution paths , then we say that it is exhibiting thread based multitasking or multithreading .

  • currentThread() public static thread currentThread()
  • setName() public void setName(String)
  • sleep() public static void sleep(long) throws InterruptedException
  • getName() public String getName()

Output:


  Thread details: Thread[main,5,main]
  After name change: Thread[Ravi,5,main]
  1
  2
  3
  4
  5  

Vector V/S ArrayList

  • Vector was introduced in java 1.0 while ArrayList was introduced in java 1.2
  • Vector is thread safe while ArrayList is not Thread safe. This means methods of vector class are Synchronized while methods of ArrayList are not Synchronized.
  • Vector is slow while ArrayList is fast.

StringBuffer V/S StringBuilder V/S String

  • Both the classes (StringBuffer and StringBuilder) are mutable. This means we can change the contents of the same object while if we compare them String , The String class is Immutable.
  • StringBuffer is available from java 1.0 , while StringBuilder was introduced java 5.
  • StringBuffer is thread safe while StringBuilder are not Thread safe. This means methods of StringBuilder class are Synchronized while methods of StringBuilder are not Synchronized.
  • StringBuffer os slow while StringBuilder is Fast.
  • Java recommends to use StringBuffer in multithreaded environments while StringBuffer in a single Thread environment.

Thread class Methods :


    public  int getPriority(): //Returns Thread Priority 
    public  void setPriority(int): //Sets the Priority    

Thread Priority Methods

  • public int getPriority(): Returns Thread Priority.
  • public void setPriority(int): Sets the Priority.

We must call setPriority() before calling start().

Predefined Static Final Variables in Thread Class

  • MAX_PRIORITY: Set at 10.
  • MIN_PRIORITY: Set at 1.
  • NORM_PRIORITY: Set at 5.

Examples of Setting Priority


// Increase thread priority by 2
th.setPriority(Thread.NORM_PRIORITY + 2);

// Set the highest priority
th.setPriority(Thread.MAX_PRIORITY);

// Invalid priority: Throws IllegalArgumentException
th.setPriority(11); 

Note: While setting priorities like th.setPriority(7) works, it is recommended to use predefined constants like Thread.NORM_PRIORITY for better code readability and maintainability.

What is Synchronization ?

In multithreaded environment there are many cases where two or more threads have to access a common resource. This common resource can be any thing like a file , a device or even an object.

For example consider a situation where two threads have separate documents and they want to print these documents but there is only one printer available . In this case the printer will be a SHARED RESOURCE.

If one of the threads starts printing but before the printing can finish , the thread scheduler prompts the CPU from it and allots it to the second thread. Now if the second thread starts printing then we will get ABSURD printout.

So Second thread must wait until the first threads comes out of sleep/wait period and finishes its printing process. This is called MUTUAL EXCLUSION between threads and to achieve this in Java we use SYNCHRONIZATION.

Thread Synchronization

How do you achieve thread Synchronization

To achieve Thread Synchronization Java provides us a keyword called “synchronized” This keyword is applied with shared resource and as soon as we apply it java attaches a lock with it .


public  void show()
{
  ……..
  ……..
 Thread.sleep(1000);
 ……..
………
} 

Example:


public class Printer {

    public void print(String msg) {
        try {
            System.out.print("[" + msg);
            Thread.sleep(1000);
            System.out.println("]");
        } catch (Exception ex) {
            System.out.println("main thread interrupted");
        }
    }
}

class MyThread7 extends Thread {
    private String str;
    private Printer p;

    public MyThread7(String str, Printer p) {
        this.str = str;
        this.p = p;
        start();
    }

    public void run() {
        synchronized(p) {
            p.print(this.str);
        }
    }
}

class UseMyThread7 {
    public static void main(String[] args) {
        String s1 = new String("Hello User");
        String s2 = new String("Java Rocks");
        String s3 = new String("Multithreading is fun");
        
        Printer obj = new Printer();
        MyThread7 m1 = new MyThread7(s1, obj);
        MyThread7 m2 = new MyThread7(s2, obj);
        MyThread7 m3 = new MyThread7(s3, obj);

        try {
            m1.join();
            m2.join();
            m3.join();
        } catch (Exception ex) {
            System.out.println("main thread interrupted");
        }
    }
}

Synchronization and Locking

  • Synchronization ensures that only one thread accesses a critical section of code at a time, preventing race conditions.
  • Explicit locking can provide finer control over thread execution compared to intrinsic locking using the synchronized keywords.

Avoiding Deadlock

  • Deadlock occurs when two threads are waiting for each other to release resources, resulting in both being blocked indefinitely.
  • Strategies to prevent deadlock include ensuring consistent resource acquisition orders among threads.

Thread Communication

  • Communication between threads can prevent busy waiting, which wastes CPU resources, by using methods like wait, notify, and notifyAll.
  • A producer-consumer model is often cited as a significant example of thread communications.

Thread Pools and Executor Framework

  • The Executor framework simplifies thread management by allowing developers to manage thread pools rather than creating and destroying threads manually.
  • Key components of the framework include Executor, ExecutorService, and ScheduledExecutorService.

Conclusion

The artical provides a comprehensive overview of Java multithreading, covering essential concepts, management techniques, synchronization, deadlock prevention, communication, and the executor frameworks.

Explore our more articles

What is Thread in Java

A thread is identified as the smallest unit of execution within a process, with multiple threads able to run independently while sharing resources.

What is Multithreading in Java

Multithreading in java provides the fecility to executing multiple threads within a single process at the same time concurrently.

– It utilizes CPU resources effectively, enhancing multitasking performance.
– Multithreading has ability to perform more then one task at a time parallelly there are two types of multithreading

What is Besic of Thread Management in Java

Java supports multithreading through its thread class and the Runnable interface, enabling developers to create concurrent applications.
Creating threads can be done by extending the Thread class or implementing the Runnable interface.

What is Synchronization and Locking in Java

In multithreaded environment there are many cases where two or more threads have to access a common resource. This common resource can be any thing like a file , a device or even an object.

For example consider a situation where two threads have separate documents and they want to print these documents but there is only one printer available . In this case the printer will be a SHARED RESOURCE.

If one of the threads starts printing but before the printing can finish , the thread scheduler prompts the CPU from it and allots it to the second thread. Now if the second thread starts printing then we will get ABSURD printout.

So Second thread must wait until the first threads comes out of sleep/wait period and finishes its printing process. This is called MUTUAL EXCLUSION between threads and to achieve this in Java we use
SYNCHRONIZATION.

Implement Multithreading using Java

We can implement multithreading using Java in two ways

-By Extending java.lang.Thread class
-By Implementing an interface called java.lang.Runnable

1 thought on “Multithreading in Java – Implement Multithreading using Java”

Leave a Comment