SlideShare a Scribd company logo
Introduction to Java Programming Language
UNIT-12
[Threads : Single and Multitasking, Creating and terminating the thread, Single and Multi tasking using
threads, Deadlock of threads, Thread communication.]
A thread, also called a lightweight process, is a single sequential flow of programming operations,
with a definite beginning and an end. A thread by itself is not a program because it cannot run on its
own. Instead, it runs within a program. The following figure shows a program with 3 threads
running under a single CPU:
Java has built-in support for concurrent programming by running multiple threads concurrently
within a single program. The term "concurrency" refers to doing multiple tasks at the same time.
Multiprocessing and multithreading, both are used to achieve multitasking.
Multi-Tasking
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 separate 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.
Provided By Shipra Swati
Introduction to Java Programming Language
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Life Cycle of a thread:
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. 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) 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.
Provided By Shipra Swati
Introduction to Java Programming Language
Creating and terminating thread
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
1. Thread creation by extending the java.lang.Thread class
We create a class that extends the java.lang.Thread class. For creating a thread a class have to
extend the Thread Class. For creating a thread by this procedure you have to follow these steps:
1. Extend the java.lang.Thread Class.
2. Override the run( ) method in the subclass from the Thread class to define the code
executed by the thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor by
subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for
running.
Example:
Class MyThread extends Thread{
  String s=null;
  MyThread(String s1){
  s=s1;
  start();
  }
  public void run(){
  System.out.println(s);
  }
}
public class RunThread{
  public static void main(String args[]){
  MyThread m1=new MyThread("Thread started....");
 }
}
2. Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the Runnable Interface is as follows:
1. A Class implements the Runnable Interface, override the run() method to define the code
executed by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.
Provided By Shipra Swati
Introduction to Java Programming Language
Example:
class MyThread1 implements Runnable{
  Thread t;
  String s=null;
 MyThread1(String s1){
  s=s1;
  t=new Thread(this);
  t.start();
  }
  public void run(){
  System.out.println(s);
 }
}
public class RunableThread{
  public static void main(String args[]){
  MyThread1 m1=new MyThread1("Thread started....");
  }
}
Stopping a thread
1. Using A boolean Variable: In this method, we declare one boolean variable called flag in a
thread. Initially we set this flag as true. Keep the task to be performed in while loop inside the run()
method by passing this flag. This will make thread continue to run until flag becomes false. We
have defined stopRunning() method. This method will set the flag as false and stops the thread.
Whenever you want to stop the thread, just call this method. Also notice that we have declared flag
as volatile. This will make thread to read its value from the main memory, thus making sure that
thread always gets its updated value.
Provided By Shipra Swati
Introduction to Java Programming Language
class MyThread extends Thread{
    //Initially setting the flag as true
     private volatile boolean flag = true;
     
    //This method will set flag as false     
    public void stopRunning(){
        flag = false;
    }
     
    @Override
    public void run()    {
        //Keep the task in while loop         
        //This will make thread continue to run until flag becomes 
false         
        while (flag)        {
            System.out.println("I am running....");
        }
         
        System.out.println("Stopped Running....");
    }
}
 
public class MainClass {   
    public static void main(String[] args)   {
        MyThread thread = new MyThread();
         
        thread.start();         
        try {
            Thread.sleep(100);
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
         
        //call stopRunning() method whenever you want to stop a 
thread         
        thread.stopRunning();
    }    
}
2. Using interrupt() Method?
In this method, we use interrupt() method to stop a thread. Whenever you call interrupt() method on
a thread, it sets the interrupted status of a thread. This status can be obtained by interrupted()
method. This status is used in a while loop to stop a thread.
Provided By Shipra Swati
Introduction to Java Programming Language
class MyThread extends Thread{    
    @Override
    public void run()  {
        while (!Thread.interrupted())  {
            System.out.println("I am running....");
        }
         
        System.out.println("Stopped Running.....");
    }
}
 
public class MainClass {   
    public static void main(String[] args) {
        MyThread thread = new MyThread();         
        thread.start();         
        try   {
            Thread.sleep(100);
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
         
        //interrupting the thread         
        thread.interrupt();
    }    
}
Deadlock of threads
Deadlock in java is a part of multithreading. 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 deadlock.
Provided By Shipra Swati
Introduction to Java Programming Language
public class TestDeadlockExample1 {  
  public static void main(String[] args) {  
    final String resource1 = "PSCET";  
    final String resource2 = "CSE JAVA";  
    // 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();  
  }  
}  
Output: Thread 1: locked resource 1
Thread 2: locked resource 2
Provided By Shipra Swati
Introduction to Java Programming Language
Thread communication
Thread communication is also termed as Inter-thread communication or Co-operation, which is
all about allowing synchronized threads to communicate with each other. 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, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait() throws
InterruptedException.
waits until object is notified.
public final void wait(long timeout) throws
InterruptedException
waits for the specified amount of time.
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. Syntax:
public final void notifyAll()
Example:
class Customer{  
   int amount=10000;    
   synchronized void withdraw(int amount){  
   System.out.println("going to withdraw...");  
         if(this.amount<amount){  
              System.out.println("Less balance; waiting for deposit...")
;  
               try{
Provided By Shipra Swati
Introduction to Java Programming Language
                   wait();
               }catch(Exception e){}  
   }  
   this.amount­=amount;  
   System.out.println("withdraw completed...");  
}  
 synchronized void deposit(int amount){  
    System.out.println("going to deposit...");  
    this.amount+=amount;  
    System.out.println("deposit completed... ");  
    notify();  
 }  
}  
class Test{  
   public static void main(String args[]){  
       final Customer c=new Customer();  
              new Thread(){  
                public void run(){
                            c.withdraw(15000);
                }  
               }.start();  
             new Thread(){  
               public void run(){
                           c.deposit(10000);
               }  
        }.start();  
}} 
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Related Questions
1. Explain Deadlock in a thread with the help of a program. [Year 2013]
2. Write note on Thread Communication. [Year 2015]
3. Define Thread Class. [Year 2016]
Provided By Shipra Swati

More Related Content

PDF
javathreads
PDF
Java Thread Synchronization
PPTX
Multithread Programing in Java
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
ODP
Multithreading In Java
PPT
Thread model in java
PPSX
Multithreading in-java
PPT
Basic of Multithreading in JAva
javathreads
Java Thread Synchronization
Multithread Programing in Java
Advanced Introduction to Java Multi-Threading - Full (chok)
Multithreading In Java
Thread model in java
Multithreading in-java
Basic of Multithreading in JAva

What's hot (20)

PPT
Threads in Java
PPT
Synchronization.37
PDF
Threads concept in java
PPT
Java Threads and Concurrency
PPT
Java multi threading
PDF
Programming with Threads in Java
PPT
Thread
PPT
Java thread
PDF
Java threading
PPTX
Thread model of java
PPT
Java And Multithreading
PPTX
Multi threading
PPTX
L22 multi-threading-introduction
PPTX
Multithreading in java
PPT
Java Multithreading
PPTX
Multithreading in java
PDF
Java threads
PPT
12 multi-threading
 
PPTX
Java Thread & Multithreading
Threads in Java
Synchronization.37
Threads concept in java
Java Threads and Concurrency
Java multi threading
Programming with Threads in Java
Thread
Java thread
Java threading
Thread model of java
Java And Multithreading
Multi threading
L22 multi-threading-introduction
Multithreading in java
Java Multithreading
Multithreading in java
Java threads
12 multi-threading
 
Java Thread & Multithreading
Ad

Similar to Java unit 12 (20)

PPTX
Concept of Java Multithreading-Partially.pptx
PPTX
Multithreading in Java Object Oriented Programming language
PPTX
Threads in Java
PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
PDF
Java Threads
PDF
Java Multithreading Interview Questions PDF By ScholarHat
PPTX
multithreading,thread and processinjava-210302183809.pptx
PPTX
Multithreading in java
PDF
Class notes(week 9) on multithreading
DOCX
Class notes(week 9) on multithreading
PPT
this power point presentation is about concurrency and multithreading
PPTX
OOPS object oriented programming UNIT-4.pptx
PPT
multithreading, creating a thread and life cycle in java.ppt
PPTX
Multi-threaded Programming in JAVA
DOCX
Threadnotes
PDF
Multithreading Introduction and Lifecyle of thread
PDF
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
PPTX
Multithreading
PPT
Md09 multithreading
PPTX
Multithreading in java
Concept of Java Multithreading-Partially.pptx
Multithreading in Java Object Oriented Programming language
Threads in Java
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
Java Threads
Java Multithreading Interview Questions PDF By ScholarHat
multithreading,thread and processinjava-210302183809.pptx
Multithreading in java
Class notes(week 9) on multithreading
Class notes(week 9) on multithreading
this power point presentation is about concurrency and multithreading
OOPS object oriented programming UNIT-4.pptx
multithreading, creating a thread and life cycle in java.ppt
Multi-threaded Programming in JAVA
Threadnotes
Multithreading Introduction and Lifecyle of thread
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
Multithreading
Md09 multithreading
Multithreading in java
Ad

More from Shipra Swati (20)

PDF
Operating System-Process Scheduling
PDF
Operating System-Concepts of Process
PDF
Operating System-Introduction
PDF
Java unit 11
PDF
Java unit 14
PDF
Java unit 7
PDF
Java unit 3
PDF
Java unit 2
PDF
Java unit 1
PDF
OOPS_Unit_1
PDF
Ai lab manual
PDF
Fundamental of Information Technology - UNIT 8
PDF
Fundamental of Information Technology - UNIT 7
PDF
Fundamental of Information Technology - UNIT 6
PDF
Fundamental of Information Technology
PDF
Disk Management
PDF
File Systems
PDF
Memory Management
PDF
Deadlocks
PDF
Process Synchronization
Operating System-Process Scheduling
Operating System-Concepts of Process
Operating System-Introduction
Java unit 11
Java unit 14
Java unit 7
Java unit 3
Java unit 2
Java unit 1
OOPS_Unit_1
Ai lab manual
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology
Disk Management
File Systems
Memory Management
Deadlocks
Process Synchronization

Recently uploaded (20)

PDF
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
PDF
International Journal of Information Technology Convergence and Services (IJI...
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
PPTX
Practice Questions on recent development part 1.pptx
PDF
Introduction to Data Science: data science process
PDF
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
PPTX
The-Looming-Shadow-How-AI-Poses-Dangers-to-Humanity.pptx
PPTX
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
PDF
6th International Conference on Artificial Intelligence and Machine Learning ...
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPT
Chapter 6 Design in software Engineeing.ppt
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
PPTX
TE-AI-Unit VI notes using planning model
PDF
Top 10 read articles In Managing Information Technology.pdf
PPT
Ppt for engineering students application on field effect
PDF
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
PDF
Principles of Food Science and Nutritions
PPTX
anatomy of limbus and anterior chamber .pptx
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
International Journal of Information Technology Convergence and Services (IJI...
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
Practice Questions on recent development part 1.pptx
Introduction to Data Science: data science process
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
The-Looming-Shadow-How-AI-Poses-Dangers-to-Humanity.pptx
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
6th International Conference on Artificial Intelligence and Machine Learning ...
Lesson 3_Tessellation.pptx finite Mathematics
Chapter 6 Design in software Engineeing.ppt
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
TE-AI-Unit VI notes using planning model
Top 10 read articles In Managing Information Technology.pdf
Ppt for engineering students application on field effect
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
Principles of Food Science and Nutritions
anatomy of limbus and anterior chamber .pptx

Java unit 12

  • 1. Introduction to Java Programming Language UNIT-12 [Threads : Single and Multitasking, Creating and terminating the thread, Single and Multi tasking using threads, Deadlock of threads, Thread communication.] A thread, also called a lightweight process, is a single sequential flow of programming operations, with a definite beginning and an end. A thread by itself is not a program because it cannot run on its own. Instead, it runs within a program. The following figure shows a program with 3 threads running under a single CPU: Java has built-in support for concurrent programming by running multiple threads concurrently within a single program. The term "concurrency" refers to doing multiple tasks at the same time. Multiprocessing and multithreading, both are used to achieve multitasking. Multi-Tasking 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 separate 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. Provided By Shipra Swati
  • 2. Introduction to Java Programming Language But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation etc. Life Cycle of a thread: The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: 1. New 2. Runnable 3. Running 4. 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) 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. Provided By Shipra Swati
  • 3. Introduction to Java Programming Language Creating and terminating thread Threads can be created by using two mechanisms : 1. Extending the Thread class 2. Implementing the Runnable Interface 1. Thread creation by extending the java.lang.Thread class We create a class that extends the java.lang.Thread class. For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps: 1. Extend the java.lang.Thread Class. 2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread. 3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor. 4. Invoke the start( ) method on the instance of the class to make the thread eligible for running. Example: Class MyThread extends Thread{   String s=null;   MyThread(String s1){   s=s1;   start();   }   public void run(){   System.out.println(s);   } } public class RunThread{   public static void main(String args[]){   MyThread m1=new MyThread("Thread started....");  } } 2. Implementing the java.lang.Runnable Interface The procedure for creating threads by implementing the Runnable Interface is as follows: 1. A Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object. 2. Create an object of Thread Class by passing a Runnable object as argument. 3. Invoke the start( ) method on the instance of the Thread class. Provided By Shipra Swati
  • 4. Introduction to Java Programming Language Example: class MyThread1 implements Runnable{   Thread t;   String s=null;  MyThread1(String s1){   s=s1;   t=new Thread(this);   t.start();   }   public void run(){   System.out.println(s);  } } public class RunableThread{   public static void main(String args[]){   MyThread1 m1=new MyThread1("Thread started....");   } } Stopping a thread 1. Using A boolean Variable: In this method, we declare one boolean variable called flag in a thread. Initially we set this flag as true. Keep the task to be performed in while loop inside the run() method by passing this flag. This will make thread continue to run until flag becomes false. We have defined stopRunning() method. This method will set the flag as false and stops the thread. Whenever you want to stop the thread, just call this method. Also notice that we have declared flag as volatile. This will make thread to read its value from the main memory, thus making sure that thread always gets its updated value. Provided By Shipra Swati
  • 5. Introduction to Java Programming Language class MyThread extends Thread{     //Initially setting the flag as true      private volatile boolean flag = true;           //This method will set flag as false          public void stopRunning(){         flag = false;     }           @Override     public void run()    {         //Keep the task in while loop                  //This will make thread continue to run until flag becomes  false                  while (flag)        {             System.out.println("I am running....");         }                   System.out.println("Stopped Running....");     } }   public class MainClass {        public static void main(String[] args)   {         MyThread thread = new MyThread();                   thread.start();                  try {             Thread.sleep(100);         }          catch (InterruptedException e) {             e.printStackTrace();         }                   //call stopRunning() method whenever you want to stop a  thread                  thread.stopRunning();     }     } 2. Using interrupt() Method? In this method, we use interrupt() method to stop a thread. Whenever you call interrupt() method on a thread, it sets the interrupted status of a thread. This status can be obtained by interrupted() method. This status is used in a while loop to stop a thread. Provided By Shipra Swati
  • 6. Introduction to Java Programming Language class MyThread extends Thread{         @Override     public void run()  {         while (!Thread.interrupted())  {             System.out.println("I am running....");         }                   System.out.println("Stopped Running.....");     } }   public class MainClass {        public static void main(String[] args) {         MyThread thread = new MyThread();                  thread.start();                  try   {             Thread.sleep(100);         }          catch (InterruptedException e) {             e.printStackTrace();         }                   //interrupting the thread                  thread.interrupt();     }     } Deadlock of threads Deadlock in java is a part of multithreading. 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 deadlock. Provided By Shipra Swati
  • 7. Introduction to Java Programming Language public class TestDeadlockExample1 {     public static void main(String[] args) {       final String resource1 = "PSCET";       final String resource2 = "CSE JAVA";       // 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();     }   }   Output: Thread 1: locked resource 1 Thread 2: locked resource 2 Provided By Shipra Swati
  • 8. Introduction to Java Programming Language Thread communication Thread communication is also termed as Inter-thread communication or Co-operation, which is all about allowing synchronized threads to communicate with each other. 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, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. Method Description public final void wait() throws InterruptedException. waits until object is notified. public final void wait(long timeout) throws InterruptedException waits for the specified amount of time. 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. Syntax: public final void notifyAll() Example: class Customer{      int amount=10000;        synchronized void withdraw(int amount){      System.out.println("going to withdraw...");            if(this.amount<amount){                 System.out.println("Less balance; waiting for deposit...") ;                  try{ Provided By Shipra Swati
  • 9. Introduction to Java Programming Language                    wait();                }catch(Exception e){}      }      this.amount­=amount;      System.out.println("withdraw completed...");   }    synchronized void deposit(int amount){       System.out.println("going to deposit...");       this.amount+=amount;       System.out.println("deposit completed... ");       notify();    }   }   class Test{      public static void main(String args[]){          final Customer c=new Customer();                 new Thread(){                   public void run(){                             c.withdraw(15000);                 }                  }.start();                new Thread(){                  public void run(){                            c.deposit(10000);                }           }.start();   }}  Output: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed Related Questions 1. Explain Deadlock in a thread with the help of a program. [Year 2013] 2. Write note on Thread Communication. [Year 2015] 3. Define Thread Class. [Year 2016] Provided By Shipra Swati