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)

1)Process-based Multitasking (Multiprocessing)
    Each process have its own address in memory i.e. each process allocates separte memory area. Process is heavyweight. Cost of communication between the process is high. Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

2)Thread-based Multitasking (Multithreading)
    Threads share the same address space. Thread is lightweight. Cost of communication between the thread is low. Note:At least one process is required for each thread.

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 ?

What we will learn in Multithreading ?
                   Multithreading Life Cycle of a Thread Two ways to create a Thread How to perform multiple tasks by multiple threads Thread Schedular Sleeping a thread Can we start a thread twice ? What happens if we call the run() method instead of start() method ? Joining a thread Naming a thread Priority of a thread Daemon Thread ShutdownHook Garbage collection Synchronization with synchronied method Synchronized block Static synchronization Deadlock Inter-thread communication

Life cycle of a Thread (Thread States)
1. Life cycle of a thread 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non-runnable and terminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM. The thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated

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.

public int setPriority(int priority): changes the priority of the thread. Thread class: Thread class provide constructors and methods to create and perform operations on a thread. public void setName(String name): changes the name of the thread. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. 15. public void start(): starts the execution of the thread. By implementing Runnable interface. .String name) Commonly used methods of Thread class: 1. public void suspend(): is used to suspend the thread(depricated). Commonly used Constructors of Thread class:     Thread() Thread(String name) Thread(Runnable r) Thread(Runnable r. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. 8. 10. 13. public int getPriority(): returns the priority of the thread. 2. 16. public int getId(): returns the id of the thread. public Thread. 7.State getState(): returns the state of the thread. 14.How to create thread: There are two ways to create a thread: 1. public String getName(): returns the name of the thread. 6. By extending Thread class 2. public void stop(): is used to stop the thread(depricated). public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 11. public void run(): is used to perform action for a thread. 3. public Thread currentThread(): returns the reference of currently executing thread. public void resume(): is used to resume the suspended thread(depricated). public boolean isAlive(): tests if the thread is alive. 17.Thread class extends Object class and implements Runnable interface. 9. 5. 12. public void join(): waits for a thread to die. 4.JVM calls the run() method on the thread.

Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.println("thread is running.  The thread moves from New state to the Runnable state. public static boolean interrupted(): tests if the current thread has been interrupted..start(). } public static void main(String args[]){ Multi t1=new Multi(). public void run(): is used to perform action for a thread. Runnable interface have only one method named run(). } } Output:thread is running..out. its target run() method will run.. 1. Starting a thread: start() method of Thread class is used to start a newly created thread. public boolean isInterrupted(): tests if the thread has been interrupted. public boolean isDaemon(): tests if the thread is a daemon thread. It performs following tasks:  A new thread starts(with new callstack).  When the thread gets a chance to execute. t1. public void interrupt(): interrupts the thread. 22.. 20. 19. 1)By extending Thread class: class Multi extends Thread{ public void run(){ System. . 21. public void setDaemon(boolean b): marks the thread as daemon or user thread.18.").

Multi t3=new Multi().").So your Multi class object is thread object now.out. ..your class constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by super() as first statement). Multi t2=new Multi(). } public static void main(String args[]){ Multi3 m1=new Multi3(). have only one run() method.When you create object of Multi class.So you need to explicitely create Thread class object. 2)By implementing the Runnable interface: class Multi3 implements Runnable{ public void run(){ System.. } public static void main(String args[]){ Multi t1=new Multi()...your class object would not be treated as a thread object. } } Output:thread is running.out. How to perform single task by multiple threads? If you have to perform single task by many threads.For example: //Program of performing single task by multiple threads class Multi extends Thread{ public void run(){ System. If you are not extending the Thread class.println("task one").start().println("thread is running.Who makes your class object as thread object? Thread class constructor allocates a new thread object. t1.We are passing the object of your class that implements Runnable so that your class run() method may execute. Thread t1 =new Thread(m1).

t1.start(). } } Output:task one task one . t3.start().t1. } } Output:task one task one task one //Program of performing single task by multiple threads class Multi3 implements Runnable{ public void run(){ System. } public static void main(String args[]){ Thread t1 =new Thread(new Multi3()).start().println("task one"). t2.start().start().//passing annonymous object of Multi3 class Thread t2 =new Thread(new Multi3()).out. t2.

println("task one").println("task two").For example: //Program of performing two tasks by two threads class Simple1 extends Thread{ public void run(){ System. } } class Test{ .out. } } class Simple2 extends Thread{ public void run(){ System. How to perform multiple tasks by multiple threads (multtasking in multithreading)? If you have to perform multiple tasks by multiple threads.have multiple run() methods.out.Note: Each thread run in a separate callstack.

} } Output:task one task two Same example as above by annonymous class that implements Runnable interface: .start(). t2. t1.public static void main(String args[]){ Simple1 t1=new Simple1().start().println("task two"). t1.start().println("task one"). t2. Thread t2=new Thread(){ public void run(){ System. } } Output:task one task two Same example as above by annonymous class that extends Thread class: //Program of performing two tasks by two threads class Test{ public static void main(String args[]){ Thread t1=new Thread(){ public void run(){ System. } }. Simple2 t2=new Simple2().out.out. } }.start().

. Runnable r2=new Runnable(){ public void run(){ System. a task executes for a predefined slice of time and then reenters the pool of ready tasks. Thread t1=new Thread(r1). t1.println("task one"). Thread t2=new Thread(r1).start().println("task two"). } } Output:task one task two The Thread Schedular:     The thread scheduler is the part of the JVM that decides which thread should run. } }. The scheduler then determines which task should execute next.out. Only one thread at a time can run in a single process. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling.start(). Under time slicing. t2. } }. The thread schedular mainly uses preemptive or time slicing scheduling to schedule the threads. There is no guarantee that which runnable thread will be chosen to run by the thread schedular.out. the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. based on priority and other factors.//Program of performing two tasks by two threads class Test{ public static void main(String args[]){ Runnable r1=new Runnable(){ public void run(){ System.

Sleeping a thread (sleep() method): The sleep() method of Thread class is used to sleep a thread for the specified time. For Example: class Multi extends Thread{ public void run(){ System.out. } . int nanos)throws InterruptedException //Program of sleep() method class Multi extends Thread{ public void run(){ for(int i=1..Syntax: Syntax of sleep() method: The Thread class provides two methods for sleeping a thread:  public static void sleep(long miliseconds)throws InterruptedException  public static void sleep(long miliseconds."). Can we start a thread twice? No.println("running.. it can never be started again. After staring a thread. an IllegalThreadStateException is thrown.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.the thread shedular picks up another thread and so on. If you sleep a thread for the specified time. If you does so.

Invoking the run() method from main thread.. t1. } public static void main(String args[]){ Multi t1=new Multi().out.start(). but does not start a separate call stack } } Output:running..println("running. t1.lang.//fine. } } Output:running Exception in thread "main" java. .").public static void main(String args[]){ Multi t1=new Multi().IllegalThreadStateException What if we call run() method directly instead start() method?   Each thread starts in a separate call stack.run().start(). class Multi extends Thread{ public void run(){ System.. the run() method goes onto the current call stack rather than at the beginning of a new call stack.. t1.

sleep(500). } } public static void main(String args[]){ Multi t1=new Multi().println(i). }catch(Exception e){System. it causes the currently running threads to stop executing until the thread it joins with completes its task.} System.out.//Problem if you direct call run() method class Multi extends Thread{ public void run(){ for(int i=1.println(e). .i<=5. Multi t3=new Multi().i++){ try{ Thread.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. Multi t2=new Multi(). In other words.out. The join() method: The join() method waits for a thread to die.

try{ .t1. t1.i<=5.out. try{ t1.sleep(500).println(e). } } Output:1 2 3 4 5 1 1 2 2 3 3 4 4 5 5 As you can see in the above example. Multi t3=new Multi().out.i++){ try{ Thread.start(). } } public static void main(String args[]){ Multi t1=new Multi(). Multi t2=new Multi(). }catch(Exception e){System.} System. }catch(Exception e){System.println(i). //Example of join(long miliseconds) method class Multi extends Thread{ public void run(){ for(int i=1.} t2.start().start().when t1 completes its task then t2 and t3 starts executing.out.println(e).join(). t3.start().

out. } public static void main(String args[]){ Multi6 t1=new Multi6().println(e).println("Name of t1:"+t1.setName(String) and getId() method: public String getName() public void setName(String name) public long getId() class Multi6 extends Thread{ public void run(){ System..out.. System.} t2.start().out.out.getId()). t3. }catch(Exception e){System.t1.getName()).out. getName(). t1. Multi6 t2=new Multi6().join(1500).start().getName()). . System.println("Name of t2:"+t2.").println("id of t1:"+t1. System.start().println("running. } } 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.

.getName()).. The currentThread() method: The currentThread() method returns a reference to the currently executing thread object. Syntax: public static Thread currentThread() //Example of currentThread() method class Multi6 extends Thread{ public void run(){ System.t2. t1.out. After changling name of t1:Sonoo Jaiswal running.out. System. t1.setName("Sonoo Jaiswal").start()..println(Thread. t2..getName()).start(). } } Output:Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running.currentThread(). } } Output:Thread-0 Thread-1 Naming a thread: . Multi6 t2=new Multi6(). } } public static void main(String args[]){ Multi6 t1=new Multi6().println("After changing name of t1:"+t1.start().

getName()). public String getName(): is used to return the name of a thread.. . 1..getName()). Example of naming a thread: class Multi6 extends Thread{ public void run(){ System. After changling name of t1:Sonoo Jaiswal running. } } Output:Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running.println("running. t2. } public static void main(String args[]){ Multi6 t1=new Multi6(). Syntax of currentThread() method:  public static Thread currentThread(): returns the reference of currently running thread. System.println("After changing name of t1:"+t1.start(). System..start(). t1. System.out.println("Name of t2:"+t2. t1.. public void setName(String name): is used to change the name of a thread.out. 2.println("Name of t1:"+t1.. The currentThread() method: The currentThread() method returns a reference to the currently executing thread object.getName()).out.setName("Sonoo Jaiswal").").The Thread class provides methods to change and get the name of a thread. Multi6 t2=new Multi6()..out.

Priorities are represented by a number between 1 and 10. thread schedular schedules the threads according to their priority (known as preemptive scheduling).start().getName()).println("running thread name is:"+Thread. public static int MAX_PRIORITY Default priority of a thread is 5 (NORM_PRIORITY).Example of currentThread() method: class Multi6 extends Thread{ public void run(){ System.out. . Multi6 t2=new Multi6().start(). In most cases. But it is not guaranteed because it depends on JVM specifification that which sheduling it chooses. public static int MIN_PRIORITY 2.currentThread(). } } Output:Thread-0 Thread-1 Priority of a Thread (Thread Priority): Each thread have a priority. t1. public static int NORM_PRIORITY 3.println(Thread.currentThread(). } } public static void main(String args[]){ Multi6 t1=new Multi6(). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10. Example of priority of a Thread: class Multi10 extends Thread{ public void run(){ System. t2.getName()).out. 3 constants defiend in Thread class: 1.

MAX_PRIORITY). m1. Its life depends on user threads.System.setPriority(Thread. } } Output:running running running running thread thread thread thread name is:Thread-0 priority is:10 name is:Thread-1 priority is:1 Daemon Thread: There are two types of threads user thread and daemon thread.println("running thread priority is:"+Thread.Thread class provides two methods related to daemon thread  public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread. why should JVM keep running this thread.lang. . } public static void main(String args[]){ Multi10 m1=new Multi10(). It has no role in life than to serve user threads.start(). 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.getPriority()). when all the user threads dies. The daemon thread is a service provider thread. Its life depends on the user threads i. If there is no user thread.setPriority(Thread. m2. m1.currentThread().start().MIN_PRIORITY). JVM termintates this thread automatically. It is a low priority thread. It provides services to the user thread.out.e. Multi10 m2=new Multi10(). Points to remember for Daemon Thread:    It provides services to user threads for background supporting tasks. That is why JVM terminates the daemon thread if there is no user thread. m2. Methods for Daemon thread: The java.

currentThread().getName()). MyThread t2=new MyThread().println("Name: "+Thread. t1. System.println("Daemon: "+Thread. t1.out. it must not be started otherwise it will throw IllegalThreadStateException.start(). class MyThread extends Thread{ public void run(){ System.getName()).println("Daemon: "+Thread. t1.currentThread(). System.out.setDaemon(true). } public static void main(String[] args){ MyThread t1=new MyThread(). public boolean isDaemon(): is used to check that current is daemon.currentThread(). } public static void main(String[] args){ MyThread t1=new MyThread().out. } } Output:Name: thread-0 Daemon: true Name: thread-1 Daemon: false Note: If you want to make a user thread as Daemon. Simple example of Daemon thread: class MyThread extends Thread{ public void run(){ System. t1.start(). MyThread t2=new MyThread().//will throw exception here .isDaemon()).out.isDaemon()).currentThread().println("Name: "+Thread. t2.setDaemon(true).start().

e=null.t2. Garbage Collection is process of reclaiming the runtime unused memory automatically. Employee e2=new Employee(). 1) By nulling a reference: Employee e=new Employee(). It is automatically done by the garbage collector so we don't need to make extra efforts. garbage means unreferenced objects.IllegalThreadStateException Garbage Collection: In java. Advantage of Garbage Collection:   It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.lang.start(). 2) By assigning a reference to another: Employee e1=new Employee(). How can an object be unreferenced? There    are By By By many ways: nulling the reference assigning a reference to another annonymous object etc. . } } Output:exception in thread main: java.

finalize() method: The finalize() method is invoked each time before the object is garbage collected. you can use finalize method to perform cleanup processing (destroying remaining objects). This thread calls the finalize() method before object is garbage collected.e1=e2. This method is defined in System class as: protected void finalize(){} Note: The Garbage collector of JVM collects only those objects that are created by new keyword. This method can be used to perform cleanup processing. 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. public static void gc(){} Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). Simple Example of garbage collection: . So if you have created any object without new.//now the first object refered by e1 is available for garbage collection 3) By annonymous object: new Employee().

Thread Synchronization Here. Synchronization Synchronization is the capabilility of control the access of multiple threads to any shared resource. Simple s2=new Simple().out. Types of Synchronization There are two types of synchronization 1. To prevent consistency problem.println("object is garbage collected"). s2=null.gc(). } } Output:object is garbage collected object is garbage collected Note: Neither finalization nor garbage collection is guaranteed. Process Synchronization 2. s1=null. Why use Synchronization? The synchronization is mainly used to 1. System.} public static void main(String args[]){ Simple s1=new Simple(). . we will discuss only thread synchronization. 2. Thread Synchronization There are two types of thread synchronization mutual exclusive and inter-thread communication.class Simple{ public void finalize(){System. To prevent thread interference. Synchronization is better in case we want only one thread can access the shared resource at a time.

By convention. by synchronized block 3.i++){ System.i<=5. and then release the lock when it's done with them. try{ Thread. Synchronized method. Let's see the example: Class Table{ void printTable(int n){//method not synchronized for(int i=1.} } } } .println(n*i).sleep(400).util. by synchronized method 2.out.concurrent. }catch(Exception e){System. 2. Cooperation (Inter-thread communication) Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data.println(e). This can be done by three ways in java: 1. Understanding the problem without Synchronization In this example.  Mutual Exclusive 1. From Java 5 the package java. a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them. by static synchronization Understanding the concept of Lock Synchronization is built around an internal entity known as the lock or monitor.locks contains several lock implementations.out. 3. so output is inconsistent. there is no synchronization. Synchronized block.Every object has an lock associated with it. static synchronization.

} public void run(){ t.start(). MyThread2(Table t){ this. } } class Use{ public static void main(String args[]){ Table obj = new Table(). MyThread1(Table t){ this.class MyThread1 extends Thread{ Table t.t=t. } public void run(){ t.printTable(5). } } Output: 5 100 10 200 15 300 20 400 25 500 Solution by synchronized method .t=t.start(). t2. } } class MyThread2 extends Thread{ Table t.printTable(100). t1. MyThread2 t2=new MyThread2(obj).//only one object MyThread1 t1=new MyThread1(obj).

MyThread1(Table t){ this.out. } public void run(){ t.sleep(400). } } class MyThread2 extends Thread{ Table t. it automatically acquires the lock for that object and releases it when the method returns. } } class Use{ . } public void run(){ t. When a thread invokes a synchronized method.} } } } class MyThread1 extends Thread{ Table t.t=t.out.printTable(100). try{ Thread. MyThread2(Table t){ this. //Program of synchronized method Class Table{ synchronized void printTable(int n){//synchronized method for(int i=1.i<=5. it is known as synchronized method.println(e).   If you declare any method as synchronized.printTable(5). }catch(Exception e){System.t=t.println(n*i). Synchronized method is used to lock an object for any shared resource.i++){ System.

i<=5.sleep(400). }catch(Exception e){System.out.//only one object MyThread1 t1=new MyThread1(obj).println(n*i).i++){ System. //Program of synchronized method by using annonymous class Class Table{ synchronized void printTable(int n){//synchronized method for(int i=1. MyThread2 t2=new MyThread2(obj).} } } } class Use{ public static void main(String args[]){ . t2.public static void main(String args[]){ Table obj = new Table(). } } Output: 5 10 15 20 25 100 200 300 400 500 Same Example of synchronized method by using annonymous class In this program.println(e). so less coding is required. try{ Thread. t1.start().start(). we have created the two threads by annonymous class.out.

printTable(100). Scope of synchronized block is smaller than the method.start(). } }.//only one object MyThread1 t1=new MyThread1(){ public void run(){ obj. t2. you can use synchronized block. Syntax to use synchronized block . MyThread1 t2=new MyThread1(){ public void run(){ obj. but you want to synchronize only 5 lines. } }.start(). If you put all the codes of the method in the synchronized block. Points to remember for Synchronized block   Synchronized block is used to lock an object for any shared resource. } } 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. it will work same as the synchronized method. t1. Suppose you have 50 lines of code in your method.printTable(5).final Table obj = new Table().

} } class MyThread2 extends Thread{ Table t. .out.println(e). MyThread1(Table t){ this.t=t.synchronized (object reference expression) { //code block } Example of synchronized block Let's see the simple example of synchronized block.println(n*i).i<=5.printTable(5). //Program of synchronized block class Table{ void printTable(int n){ synchronized(this){//synchronized block for(int i=1. MyThread2(Table t){ this.sleep(400). } public void run(){ t.} } } }//end of the method } class MyThread1 extends Thread{ Table t.printTable(100).t=t.out. try{ Thread.i++){ System. }catch(Exception e){System. } public void run(){ t.

sleep(400).i++){ System.start().out.} } class Use{ public static void main(String args[]){ Table obj = new Table().i<=5.//only one object MyThread1 t1=new MyThread1(obj). MyThread2 t2=new MyThread2(obj).println(n*i). } } Output:5 10 15 20 25 100 200 300 400 500 Same Example of synchronized block by using annonymous class: //Program of synchronized block by using annonymous class class Table{ void printTable(int n){ synchronized(this){//synchronized block for(int i=1. try{ Thread. t1.} } } }//end of the method } . t2.println(e).start().out. }catch(Exception e){System.

Thread t2=new Thread(){ public void run(){ obj. t2. } } 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. t1. } }.printTable(5).start(). } }.start().printTable(100). .class Use{ public static void main(String args[]){ final Table obj = new Table().//only one object Thread t1=new Thread(){ public void run(){ obj.

i++){ System.In case of synchonized method and synchronized block there cannot be inteference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock. Example of static synchronization In this example we are applying synchronized keyword on the static method to perform statis synchrnization.i<=10. class Table{ synchronized static void printTable(int n){ for(int i=1.Static synchronization solves this problem.I want no interference between t1 and t3 or t2 and t4.out. Table) named object1 and object2.println(n*i).Problem without static synchronization Suppose there are two objects of a shared class(e. try{ Thread. }catch(Exception e){} } } } .sleep(400).But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.g.

MyThread2 t2=new MyThread2(). } } class Use{ public static void main(String t[]){ MyThread1 t1=new MyThread1().printTable(10).start(). t4.class MyThread1 extends Thread{ public void run(){ Table.printTable(1000). MyThread4 t4=new MyThread4(). t3. } } class MyThread2 extends Thread{ public void run(){ Table.start(). } } class MyThread4 extends Thread{ public void run(){ Table. t2. MyThread3 t3=new MyThread3().start(). t1. } } Output: 1 2 . } } class MyThread3 extends Thread{ public void run(){ Table.start().printTable(100).printTable(1).

we are using annonymous class to create the threads.println(n*i). class Table{ synchronized static void printTable(int n){ for(int i=1.i<=10.out.i++){ System.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 Same example of static synchronization by annonymous class In this example. try{ .

Thread t3=new Thread(){ public void run(){ Table.printTable(10).printTable(1). t1. Thread t4=new Thread(){ public void run(){ Table.start().sleep(400).printTable(100).printTable(1000). } } Output: 1 2 . } }.start(). }catch(Exception e){} } } } public class Test { public static void main(String[] args) { Thread t1=new Thread(){ public void run(){ Table. } }. t4.start(). } }. Thread t2=new Thread(){ public void run(){ Table.start(). t3.Thread. t2. } }.

. } } // Synchronized block on class A .class. A static synchronized method printTable(int n) in class Table is equivalent to the following declaration: static void printTable(int n) { synchronized (Table.class) { // .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 Synchronized block on a class lock: The block synchronizes on the lock of the object denoted by the reference ..

Since.out. final String resource2 = "vimal jaiswal". // t1 tries to lock resource1 then resource2 Thread t1 = new Thread() { public void run() { synchronized (resource1) { System.sleep(100).Deadlock: Deadlock can occur in a situation when a thread is waiting for an object lock.} catch (Exception e) {} synchronized (resource2) { System.println("Thread 1: locked resource 1"). Example of Deadlock in java: public class DeadlockExample { public static void main(String[] args) { final String resource1 = "ratan jaiswal". // t2 tries to lock resource2 then resource1 Thread t2 = new Thread() { public void run() { synchronized (resource2) { . that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. try { Thread.out. the condition is called daedlock. both threads are waiting for each other to release the lock. } } } }.println("Thread 1: locked resource 2").

t1. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. try { Thread.sleep(100).println("Thread 2: locked resource 2"). one of them is chosen to be awakened. The choice is arbitrary . or a specified amount of time has elapsed.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.System. The current thread must own this object's monitor.It is implemented by following methods of Object class:  wait()  notify()  notifyAll() 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.println("Thread 2: locked resource 1").out.out. If any threads are waiting on this object.start(). t2. } } Output: Thread 1: locked resource 1 Thread 2: locked resource 2 Inter-thread communication (Cooperation): Cooperation(Inter-thread communication) is all about making synchronized threads communicate with each other.start(). } } } }.} catch (Exception e) {} synchronized (resource1) { System.

} public synchronized void deposit(int amount){ System..println("withdraw completed"). } . public synchronized int withdraw(int amount){ System.Syntax: public final void notify() 3)notifyAll() method: Wakes up all threads that are waiting on this object's monitor. System.println(Thread. if(flag==0){ try{ System.amount+=amount.out.println("waiting.getName()+" is going to withdraw"). System.out. this.getName()+" is going to deposit")..println(Thread.currentThread().currentThread(). flag=1.out. public final void notifyAll() Example of Inter thread Communication: public class Customer { int amount=0.out.").amount-=amount. notifyAll(). }catch(Exception e){} } this.and occurs at the discretion of the implementation..println("deposit completed"). wait(). int flag=0.out. return amount.

println("After withdraw amount is"+c. calling the interrupt() method on the thread. breaks out the sleeping or waiting state throwing InterruptedException.amount). sleep() or wait() is invoked).withdraw(5000). calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true.out. Thread t1=new Thread(){ public void run(){ c. } } Output: Thread-0 is going to withdraw waiting.deposit(9000). t1.. Thread t2=new Thread(){ public void run(){ c. 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.start().amount).start().} public class SynMethod { public static void main(String[] args) { final Customer c=new Customer().. } }. System..e. System.println("After deposit amount is "+c. If the thread is not in the sleeping or waiting state. t2. Let's first see the methods provided by the . } }.out.

we can handle it where sleep() or wait() method is invoked.InterruptedException: sleep interrupted at A.println("task").} } } download this example Output:Exception in thread-0 java.sleep(1000).. we are propagating it.interrupt().out. }catch(Exception e){System. try{ t1. java. so it will stop working. class A extends Thread{ public void run(){ try{ Thread. } } public static void main(String args[]){ A t1=new A(). }catch(InterruptedException e){ throw new RuntimeException("Thread interrupted.run(A.println("Exception handled "+e).lang.RuntimeException: Thread interrupted. after interrupting the thread..."+e).out. Let's first see the example where we are propagating the exception.lang. The 3 methods provided by the Thread class for interrupting a thread    public void interrupt() public static boolean interrupted() public boolean isInterrupted() Example of interrupting a thread that stops working In this example.Thread class for thread interruption. System. t1. If we don't want to stop the thread.java:7) .start()..

Example of interrupting a thread that doesn't stop working In this example. System.. we handle the exception.out. Example of interrupting thread that behaves normally If thread is not in sleeping or waiting state.InterruptedException: sleep interrupted thread is running.i++) . } System.println("Exception handled "+e). t1. so it will break out the sleeping but will not stop working. t1.. calling the interrupt() method sets the interrupted flag to true that can be used to stop the thread by the java programmer later. }catch(InterruptedException e){ System.out.sleep(1000).i<=5."). } } download this example Output:Exception handled java. after interrupting the thread.. class A extends Thread{ public void run(){ for(int i=1.. } public static void main(String args[]){ A t1=new A().lang.println("thread is running.out.start(). class A extends Thread{ public void run(){ try{ Thread.println("task").interrupt().

t1.start(). } public static void main(String args[]){ A t1=new A().println(i).println("code for normal thread").out. . t1.i++){ if(Thread. The static interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is true.out. InterruptedDemo t2=new InterruptedDemo().out.println("code for interrupted thread"). } else{ System.System.interrupted()){ System. } }//end of for loop } public static void main(String args[]){ InterruptedDemo t1=new InterruptedDemo(). class InterruptedDemo extends Thread{ public void run(){ for(int i=1.interrupt().i<=2. } } Output:1 2 3 4 5 What about isInterrupted and interrupted method? The isInterrupted() method returns the interrupted flag either true or false.

start(). t2. t1.start(). } } Output:Code for interrupted thread code for normal thread code for normal thread code for normal thread .t1.interrupt().

Sign up to vote on this title
UsefulNot useful