Multithreading in Java
Multithreading in Java
Multithreading in Java
1. Multithreading 2. Multitasking 3. Process-based multitasking 4. Thread-based multitasking 5. What is Thread Multithreading is a process of executing multiple threads simultaneously. Thread is basically a lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than mulitprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and context-switching between the threads takes less time than processes. Multithreading is mostly used in games, animation etc.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: Process-based Multitasking(Multiprocessing) Thread-based Multitasking(Multithreading)
What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process.
As shown in the above figure, thread is executed inside the process. There is contextswitching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. Note:At a time only one thread is executed.
Do You Know ?
Why your class, which extends the Thread class, object is treated as thread ? Who is responsible for it ? How to perform two tasks by two threads ? How to perform multithreading by annonymous class ? What is the Thread Schedular and what is the difference between preemptive scheduling and time slicing ? What happens if we start a thread twice ? What happens if we call the run() method instead of start() method ? What is the purpose of join method ? Why JVM terminates the daemon thread if there is no user threads remaining ? What is the shutdown hook? What is garbage collection ? What is the purpose of finalize() method ? What does gc() method ? What is synchronization and why use synchronization ? What is the difference between synchronized method and synchronized block ? What are the two ways to perform static synchronization ? What is deadlock and when it can occur ? What is interthread-communication or cooperation ?
1)New
The thread is in new state if 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 if the thread scheduler has selected it.
4)Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5)Terminated
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.
18. public boolean isDaemon(): tests if the thread is a daemon thread. 19. public void setDaemon(boolean b): marks the thread as daemon or user thread. 20. public void interrupt(): interrupts the thread. 21. public boolean isInterrupted(): tests if the thread has been interrupted. 22. public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). 1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks: A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run.
class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } } Output:thread is running...
class Multi3 implements Runnable{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); t1.start(); } } Output:thread is running... If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.
t1.start(); t2.start(); t3.start(); } } Output:task one task one task one //Program of performing single task by multiple threads class Multi3 implements Runnable{ public void run(){ System.out.println("task one"); } public static void main(String args[]){ Thread t1 =new Thread(new Multi3());//passing annonymous object of Multi3 class Thread t2 =new Thread(new Multi3()); t1.start(); t2.start(); } } Output:task one task one
public static void main(String args[]){ Simple1 t1=new Simple1(); Simple2 t2=new Simple2(); t1.start(); t2.start(); } } Output:task one task two
//Program of performing two tasks by two threads class Test{ public static void main(String args[]){ Runnable r1=new Runnable(){ public void run(){ System.out.println("task one"); } }; Runnable r2=new Runnable(){ public void run(){ System.out.println("task two"); } }; Thread t1=new Thread(r1); Thread t2=new Thread(r1); t1.start(); t2.start(); } } Output:task one task two
//Program of sleep() method class Multi extends Thread{ public void run(){ for(int i=1;i Output:1 1 2 2 3 3 4 4 5 5 As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.
public static void main(String args[]){ Multi t1=new Multi(); t1.start(); t1.start(); } } Output:running Exception in thread "main" java.lang.IllegalThreadStateException
class Multi extends Thread{ public void run(){ System.out.println("running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.run();//fine, but does not start a separate call stack } } Output:running...
//Problem if you direct call run() method class Multi extends Thread{ public void run(){ for(int i=1;i Output:1 2 3 4 5 1 2 3 4 5 As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object.
Syntax:
public void join()throws InterruptedException public void join(long miliseconds)throws InterruptedException //Example of join() method class Multi extends Thread{ public void run(){ for(int i=1;i<=5;i++){ try{ Thread.sleep(500); }catch(Exception e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ Multi t1=new Multi(); Multi t2=new Multi(); Multi t3=new Multi();
t1.start(); try{ t1.join(); }catch(Exception e){System.out.println(e);} t2.start(); t3.start(); } } Output:1 2 3 4 5 1 1 2 2 3 3 4 4 5 5 As you can see in the above example,when t1 completes its task then t2 and t3 starts executing. //Example of join(long miliseconds) method class Multi extends Thread{ public void run(){ for(int i=1;i<=5;i++){ try{ Thread.sleep(500); }catch(Exception e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ Multi t1=new Multi(); Multi t2=new Multi(); Multi t3=new Multi(); t1.start(); try{
t1.join(1500); }catch(Exception e){System.out.println(e);} t2.start(); t3.start(); } } Output:1 2 3 1 4 1 2 5 2 3 3 4 4 5 5 In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing.
class Multi6 extends Thread{ public void run(){ System.out.println("running..."); } public static void main(String args[]){ Multi6 t1=new Multi6(); Multi6 t2=new Multi6(); System.out.println("Name of t1:"+t1.getName()); System.out.println("Name of t2:"+t2.getName()); System.out.println("id of t1:"+t1.getId()); t1.start();
t2.start(); t1.setName("Sonoo Jaiswal"); System.out.println("After changing name of t1:"+t1.getName()); } } Output:Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running... After changling name of t1:Sonoo Jaiswal running...
Syntax:
public static Thread currentThread() //Example of currentThread() method class Multi6 extends Thread{ public void run(){ System.out.println(Thread.currentThread().getName()); } } public static void main(String args[]){ Multi6 t1=new Multi6(); Multi6 t2=new Multi6(); t1.start(); t2.start(); } } Output:Thread-0 Thread-1
Naming a thread:
The Thread class provides methods to change and get the name of a thread. 1. public String getName(): is used to return the name of a thread. 2. public void setName(String name): is used to change the name of a thread.
class Multi6 extends Thread{ public void run(){ System.out.println("running..."); } public static void main(String args[]){ Multi6 t1=new Multi6(); Multi6 t2=new Multi6(); System.out.println("Name of t1:"+t1.getName()); System.out.println("Name of t2:"+t2.getName()); t1.start(); t2.start(); t1.setName("Sonoo Jaiswal"); System.out.println("After changing name of t1:"+t1.getName()); } } Output:Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running... After changling name of t1:Sonoo Jaiswal running...
class Multi6 extends Thread{ public void run(){ System.out.println(Thread.currentThread().getName()); } } public static void main(String args[]){ Multi6 t1=new Multi6(); Multi6 t2=new Multi6(); t1.start(); t2.start(); } } Output:Thread-0 Thread-1
class Multi10 extends Thread{ public void run(){ System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority()); } public static void main(String args[]){ Multi10 m1=new Multi10(); Multi10 m2=new Multi10(); m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start(); m2.start(); } }
Daemon Thread:
There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM termintates this thread automatically.
Why JVM termintates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
class MyThread extends Thread{ public void run(){ System.out.println("Name: "+Thread.currentThread().getName()); System.out.println("Daemon: "+Thread.currentThread().isDaemon()); } public static void main(String[] args){ MyThread t1=new MyThread(); MyThread t2=new MyThread(); t1.setDaemon(true); t1.start(); t2.start(); } }
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.
class MyThread extends Thread{ public void run(){ System.out.println("Name: "+Thread.currentThread().getName()); System.out.println("Daemon: "+Thread.currentThread().isDaemon()); } public static void main(String[] args){ MyThread t1=new MyThread(); MyThread t2=new MyThread(); t1.start(); t1.setDaemon(true);//will throw exception here
t2.start(); } }
Garbage Collection:
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically.
1) By nulling a reference:
3) By annonymous object:
new Employee();
finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in System class as:
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.
class Simple{ public void finalize(){System.out.println("object is garbage collected");} public static void main(String args[]){ Simple s1=new Simple(); Simple s2=new Simple(); s1=null; s2=null; System.gc(); } } Output:object is garbage collected object is garbage collected
Synchronization
Synchronization is the capabilility of control the access of multiple threads to any shared resource. Synchronization is better in case we want only one thread can access the shared resource at a time.
Types of Synchronization
There are two types of synchronization 1. Process Synchronization 2. Thread Synchronization Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual Exclusive 1. Synchronized method. 2. Synchronized block. 3. static synchronization. Cooperation (Inter-thread communication)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: 1. by synchronized method 2. by synchronized block 3. by static synchronization
Class Table{ void printTable(int n){//method not synchronized for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } }
class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } class Use{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } } Output: 5 100 10 200 15 300 20 400 25 500
If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the method returns.
//Program of synchronized method Class Table{ synchronized void printTable(int n){//synchronized method for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } class Use{
public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } } Output: 5 10 15 20 25 100 200 300 400 500
//Program of synchronized method by using annonymous class Class Table{ synchronized void printTable(int n){//synchronized method for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class Use{ public static void main(String args[]){
final Table obj = new Table();//only one object MyThread1 t1=new MyThread1(){ public void run(){ obj.printTable(5); } }; MyThread1 t2=new MyThread1(){ public void run(){ obj.printTable(100); } }; t1.start(); t2.start(); } } Output: 5 10 15 20 25 100 200 300 400 500
Synchronized block
<<prev
next>>
Synchronized block can be used to perform synchronization on any specific resouce of the method. Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block. If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.
//Program of synchronized block class Table{ void printTable(int n){ synchronized(this){//synchronized block for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } }//end of the method } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100);
} } class Use{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } } Output:5 10 15 20 25 100 200 300 400 500
class Use{ public static void main(String args[]){ final Table obj = new Table();//only one object Thread t1=new Thread(){ public void run(){ obj.printTable(5); } }; Thread t2=new Thread(){ public void run(){ obj.printTable(100); } }; t1.start(); t2.start(); } } Output:5 10 15 20 25 100 200 300 400 500
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
class Table{ synchronized static void printTable(int n){ for(int i=1;i<=10;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){} } } }
class MyThread1 extends Thread{ public void run(){ Table.printTable(1); } } class MyThread2 extends Thread{ public void run(){ Table.printTable(10); } } class MyThread3 extends Thread{ public void run(){ Table.printTable(100); } }
class MyThread4 extends Thread{ public void run(){ Table.printTable(1000); } } class Use{ public static void main(String t[]){ MyThread1 t1=new MyThread1(); MyThread2 t2=new MyThread2(); MyThread3 t3=new MyThread3(); MyThread4 t4=new MyThread4(); t1.start(); t2.start(); t3.start(); t4.start(); } } Output: 1 2
3 4 5 6 7 8 9 10 10 20 30 40 50 60 70 80 90 100 100 200 300 400 500 600 700 800 900 1000 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
Thread.sleep(400); }catch(Exception e){} } } } public class Test { public static void main(String[] args) { Thread t1=new Thread(){ public void run(){ Table.printTable(1); } }; Thread t2=new Thread(){ public void run(){ Table.printTable(10); } }; Thread t3=new Thread(){ public void run(){ Table.printTable(100); } }; Thread t4=new Thread(){ public void run(){ Table.printTable(1000); } }; t1.start(); t2.start(); t3.start(); t4.start(); } }
Output: 1 2
3 4 5 6 7 8 9 10 10 20 30 40 50 60 70 80 90 100 100 200 300 400 500 600 700 800 900 1000 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called daedlock.
public class DeadlockExample { public static void main(String[] args) { final String resource1 = "ratan jaiswal"; final String resource2 = "vimal jaiswal"; // t1 tries to lock resource1 then resource2 Thread t1 = new Thread() { public void run() { synchronized (resource1) { System.out.println("Thread 1: locked resource 1"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (resource2) { System.out.println("Thread 1: locked resource 2"); } } } }; // t2 tries to lock resource2 then resource1 Thread t2 = new Thread() { public void run() { synchronized (resource2) {
System.out.println("Thread 2: locked resource 2"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (resource1) { System.out.println("Thread 2: locked resource 1"); } } } };
t1.start(); t2.start(); } }
1)wait() method:
Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor.Syntax: public final void wait()throws InterruptedException public final void wait(long timeout)throws InterruptedException
2)notify() method:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.Syntax: public final void notify()
3)notifyAll() method:
Wakes up all threads that are waiting on this object's monitor. public final void notifyAll()
public class Customer { int amount=0; int flag=0; public synchronized int withdraw(int amount){ System.out.println(Thread.currentThread().getName()+" is going to withdraw"); if(flag==0){ try{ System.out.println("waiting...."); wait(); }catch(Exception e){} } this.amount-=amount; System.out.println("withdraw completed"); return amount; } public synchronized void deposit(int amount){ System.out.println(Thread.currentThread().getName()+" is going to deposit"); this.amount+=amount; notifyAll(); System.out.println("deposit completed"); flag=1; }
} public class SynMethod { public static void main(String[] args) { final Customer c=new Customer(); Thread t1=new Thread(){ public void run(){ c.withdraw(5000); System.out.println("After withdraw amount is"+c.amount); } }; Thread t2=new Thread(){ public void run(){ c.deposit(9000); System.out.println("After deposit amount is "+c.amount); } };
t1.start(); t2.start();
} }
Output: Thread-0 is going to withdraw waiting.... Thread-1 is going to deposit deposit completed After deposit amount is 9000 withdraw completed After withdraw amount is 4000
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true. Let's first see the methods provided by the
class A extends Thread{ public void run(){ try{ Thread.sleep(1000); System.out.println("task"); }catch(InterruptedException e){ throw new RuntimeException("Thread interrupted..."+e); } } public static void main(String args[]){ A t1=new A(); t1.start(); try{ t1.interrupt(); }catch(Exception e){System.out.println("Exception handled "+e);} } }
class A extends Thread{ public void run(){ try{ Thread.sleep(1000); System.out.println("task"); }catch(InterruptedException e){ System.out.println("Exception handled "+e); } System.out.println("thread is running..."); } public static void main(String args[]){ A t1=new A(); t1.start(); t1.interrupt(); } }
System.out.println(i); } public static void main(String args[]){ A t1=new A(); t1.start(); t1.interrupt(); } }
Output:1 2 3 4 5
class InterruptedDemo extends Thread{ public void run(){ for(int i=1;i<=2;i++){ if(Thread.interrupted()){ System.out.println("code for interrupted thread"); } else{ System.out.println("code for normal thread"); } }//end of for loop } public static void main(String args[]){ InterruptedDemo t1=new InterruptedDemo(); InterruptedDemo t2=new InterruptedDemo();
Output:Code for interrupted thread code for normal thread code for normal thread code for normal thread