Multithreading in Java





Unlike most other computer languages, Java provides built-in support for multithreaded programming.

  • A multithreaded program contains two or more parts that can run concurrently.

  • Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.

Benefit of Multithreading :

The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated.

One thread can pause without stopping other parts of your program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere.

Note : At a time one thread is executed only.

Life cycle of a Thread (Thread States) :

prowessapps.in

Threads exist in several states.

A thread can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

  1. New :
    The thread is in new state when you create an instance of Thread class but before the invocation of start() method.


  2. Runnable :
    The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.


  3. Running :
    The thread is in running state when the thread scheduler has selected it.


  4. Non-Runnable (Wait) :
    A thread is waiting for another thread to perform a task. In this stage the thread is still alive.


  5. Terminated :
    A thread is in terminated when its run() method exits.


Thread Priorities :

Every thread has a priority that helps the operating system determine the order in which threads are scheduled for execution. In java thread priority ranges between,

MIN-PRIORITY (a constant of 1)

MAX-PRIORITY (a constant of 10)

By default every thread is given a NORM-PRIORITY(5). The main thread always have NORM-PRIORITY.

Thread Class :

  • Thread class is the main class on which Java's Multithreading system is based.

  • Thread class provide constructors and methods to create and perform operations on a thread.


Constructors of Thread class:

  1. Thread()

  2. Thread(String name)

  3. Thread(Runnable r)

  4. Thread(Runnable r, String name)

  5. Thread(ThreadGroup gr, String name)

  6. Thread(ThreadGroup gr, Runnable r)

Thread class also defines many methods for managing and controlling threads. Some of them are,

METHODSDESCRIPTION
run()is used to perform action for a thread.
start()start a thread by calling run() method
sleep()suspend thread for a specified time
join()waits for a thread to die.
getPriority() returns the priority of the thread.
getName() returns the name of the thread.
setName()changes the name of the thread.
isAlive()checks if thread is still running or not
To get all the list use command javap java.lang.Thread

Thread Creation :

There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.


Override the method run() and call start() method to start a new thread.


by extending Thread class

class MyThread extends Thread
{  
 public void run() 
 {  
 System.out.print("thread is running");
 }  
 public static void main(String []ar)
 {
   MyThread t1=new MyThread();  
   t1.start();   
 }  
}       
OUTPUT :
thread is running

by implementing Runnable interface

class MyThread implements Runnable
{  
 public void run() 
 {  
 System.out.print("thread is running");
 }  
 public static void main(String []ar)
 {
   MyThread ob = new MyThread();
   Thread t1 = new Thread(ob); 
   t1.start(); 
 }  
}       
OUTPUT :
thread is running

Example of sleep method :

class ThreadDemo extends Thread
{
 public void run(){
  for(int i=1;i<5;i++){
    try{
      Thread.sleep(500);
  }
  catch(InterruptedException e)
   {
    System.out.println(e);
   }
  System.out.println(i);  
 }  
}  
public static void main(String args[]){
  ThreadDemo t1=new ThreadDemo();
  ThreadDemo t2=new ThreadDemo();  
   
   t1.start();
   t2.start();  
 }  
}             
OUTPUT :
1
1
2
2
3
3
4
4           

Example of join method :

public class MyThread extends Thread
{
 public void run()
  {
    System.out.println("Hello");
     try {
        Thread.sleep(500);
    	}
     catch(InterruptedException e){
       }
      System.out.println("Hi");
   }
public static void main(String[] ar)
 {
   MyThread t1=new MyThread();
   MyThread t2=new MyThread();
    t1.start(); 
    try{
         t1.join();//Waiting for t1 to finish
       }
    catch(InterruptedException e){
       }
    t2.start();
  }
}          
OUTPUT :
Hello
hi
Hello
Hi         

As you can see in the above example,when t1 completes its task then t2 starts executing.

Example : Aceess name and id of current running thread:

class MyThread extends Thread{
  @Override
public void run(){
String ct ;
ct= Thread.currentThread().getName();
System.out.print("Current Thread is :");
System.out.println(ct);
 }  
 public static void main(String []ar){
  MyThread t1=new MyThread();  
  MyThread t2=new MyThread();
  
  String nm1 = t1.getName();
  String nm2 = t2.getName();
  
  long id1 = t1.getId();
  long id2 = t2.getId();
  System.out.println("t1's Name :"+nm1);
  System.out.println("t2's Name :"+nm2);
  System.out.println("id of t1:"+id1);
  System.out.println("id of t2:"+id2);
 
  t1.setName("Java Prowess");
System.out.println("After changing name of t1:");
     System.out.println(t1.getName());
   t1.start();
   t2.start();
 }  
}           
OUTPUT :
t1's Name :Thread-0
t2's Name :Thread-1
id of t1:10
id of t2:11
After changing name of t1:Java Prowess
Current Thread is :Java Prowess
Current Thread is :Thread-1                
            

Thread Synchronization :

  • When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. As you will see, Java provides unique, language-level support for it.

  • Key to synchronization is the concept of the monitor (also called a semaphore).

  • A monitor is an object that is used as a mutually exclusive lock, or mutex.

  • Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor.

  • All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor.


Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by the following ways in java:

1. by synchronized method

2. by synchronized block

Using Synchronized Method :

  • Method declared as synchronized is known as synchronized method.

  • While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait.

Syntax :

synchronized ret-type method-name(Arg-list)
{
// Method Body
}          

Problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the example:

class MyThread1
{
 void display(String msg)
 {
  System.out.print ("[ "+msg);
  try
  {
   Thread.sleep(1000);
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  System.out.println (" ]");
 }
}

class MyThread2 extends Thread
{
 String msg;  
 MyThread1 t1;
 MyThread2 (MyThread1 fp,String str)
 {
  t1 = fp;
  msg = str;
  start();
 }
 public void run()
 {
  t1.display(msg);
  }
}

 class ThreadDemo
{
 public static void main (String []ar)
 {
  MyThread1 mt = new MyThread1();
  new MyThread2(mt, "C Prowess");
  new MyThread2 (mt,"C++ Prowess");
  new MyThread2(mt, "Java Prowess");
 }
}          
OUTPUT :
[C++ Prowess[C Prowess[Java Prowess]
]
]

Synchronized Method

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

class MyThread1
{
 synchronized void display(String msg) 
 {
  System.out.print ("[ "+msg);
  try
  {
   Thread.sleep(1000);
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  System.out.println (" ]");
 }
}

class MyThread2 extends Thread
{
 String msg;  
 MyThread1 t1;
 MyThread2 (MyThread1 fp,String str)
 {
  t1 = fp;
  msg = str;
  start();
 }
 public void run()
 {
   t1.display(msg);
 }
}

 class ThreadDemo
{
 public static void main (String []ar)
 {
  MyThread1 mt = new MyThread1();
  new MyThread2(mt, "C Prowess");
  new MyThread2 (mt,"C++ Prowess");
  new MyThread2(mt, "Java Prowess");
 }
}          
OUTPUT :
[ C Prowess ]
[ Java Prowess ]
[ C++ Prowess ]

Using Synchronized Block :

While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases.To understand why, consider the following. Imagine that you want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use methods. Further, this class was not created by you, but by a third party, and you do not have access to the source code. Thus, you can’t add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement:

synchronized(object) {
// statements to be synchronized
}

Example with Synchronization Block

class MyThread1
{
 void display(String msg)
 {
  System.out.print ("[ "+msg);
  try
  {
   Thread.sleep(1000);
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  System.out.println (" ]");
 }
}

class MyThread2 extends Thread
{
 String msg;  
 MyThread1 t1;
 MyThread2 (MyThread1 fp,String str)
 {
  t1 = fp;
  msg = str;
  start();
 }
 public void run()
 {
  synchronized(t1) 
  {
   t1.display(msg);
  }
 }
}

 class ThreadDemo
{
 public static void main (String []ar)
 {
  MyThread1 mt = new MyThread1();
  new MyThread2(mt, "C Prowess");
  new MyThread2 (mt,"C++ Prowess");
  new MyThread2(mt, "Java Prowess");
 }
}          
OUTPUT :
[ C Prowess ]
[ Java Prowess ]
[ C++ Prowess ]

Next topic is nested-classes




 









Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in



CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved