0% found this document useful (0 votes)
12 views23 pages

Java Thread Life Cycle Explained

The document explains the life cycle of threads in Java, detailing the various states a thread can be in, such as NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. It also describes how to create threads by extending the Thread class or implementing the Runnable interface, along with methods to manage thread execution like start(), sleep(), and join(). Additionally, it covers thread priorities, daemon threads, and provides examples to illustrate these concepts.

Uploaded by

rithikagoud637
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

Java Thread Life Cycle Explained

The document explains the life cycle of threads in Java, detailing the various states a thread can be in, such as NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. It also describes how to create threads by extending the Thread class or implementing the Runnable interface, along with methods to manage thread execution like start(), sleep(), and join(). Additionally, it covers thread priorities, daemon threads, and provides examples to illustrate these concepts.

Uploaded by

rithikagoud637
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Thread Life Cycle in Java

In Java, threads go through several distinct states during their lifetime, as defined
in [Link] class. All thread states are Enum constants. A thread can
be in only one state at a given point in time.
These states are virtual machine states which do not reflect any operating system
thread states. A thread can be in one of the following states:

Thread States Description

NEW A thread that has not yet started is in this state.

RUNNABLE A thread executing in the Java virtual machine is in


this state.

BLOCKED A thread that is blocked waiting for a monitor lock is


in this state.

WAITING A thread that is waiting indefinitely for another thread


to perform a particular action is in this state.

TIMED_WAITING A thread that is waiting for another thread to perform


an action for up to a specified waiting time is in this
state.

TERMINATED A thread that has exited is in this state.

Thread States

Transitions Between States


o new → start() → runnable
o runnable → scheduler picks → running
o running → wait()/join() → waiting
o running → sleep()/join(timeout) → timed waiting
o running → blocked → when trying to acquire a lock
o any state → finished/error → terminated

Example: Thread States

There are the following two ways to create a thread:


o By Extending Thread Class
o By Implementing Runnable Interface

Thread Class
The simplest way to create a thread in Java is by extending the Thread class and
overriding its run() method. Thread class provide constructors and methods to create
and perform operations on a thread. Thread class extends Object class and implements
Runnable interface.
Constructors of Thread Class
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r, String name)

Thread Class Methods


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.

By Implementing Runnable Interface


Another approach to creating threads in Java is by implementing the 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(). This approach is preferred when we want to separate the task
from the thread itself, promoting better encapsulation and flexibility.
public void run(): is used to perform action for a thread.
Starting a Thread
The start() method of the Thread class is used to start a newly created thread. It
performs the following tasks:
o A new thread starts (with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Thread Creation
1) Creating Thread by Extending Thread Class
File Name: [Link]

. class Multi extends Thread{


. public void run(){
. [Link]("thread is running...");
. }
. public static void main(String args[]){
. Multi t1=new Multi();
. [Link]();
. }
. }
Output:
thread is running...
In this example, we define a custom thread by extending the Thread class and
overriding the run() method with our desired functionality. We then instantiate the
thread and call its start() method to begin execution.
2) Java Thread Example by implementing Runnable interface
FileName: [Link]

. class Multi3 implements Runnable{


. public void run(){
. [Link]("thread is running...");
. }
.
. public static void main(String args[]){
. Multi3 m1=new Multi3();
. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
. [Link]();
. }
. }
Output:
thread is running...
In this example, we define a class MyRunnable that implements the Runnable
interface and provides the task logic inside its run() method. We then create a new
Thread object, passing an instance of MyRunnable to its constructor, and start the
thread using the start() method.
If we are not extending the Thread class, the class object would not be treated as a
thread object. So, we need to explicitly create the Thread class object. We are passing
the object of our class that implements Runnable so that the class's run() method may
execute.

class MyThread extends Thread {


private int start, end;
MyThread(int start, int end) {
[Link] = start;
[Link] = end;
}
public void run() {
for (int i = start; i <= end; i++) {
[Link](i);
}
}
}
public class MultiThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread(1, 5); // prints 1–5
MyThread t2 = new MyThread(6, 10); // prints 6–10
[Link]();
[Link]();
}
}

class MyThread extends Thread {


private int start, end;

MyThread(int start, int end) {


[Link] = start;
[Link] = end;
}

public void run() {


for (int i = start; i <= end; i++) {
[Link](i);
try {
[Link](500); // pause for 0.5 seconds
} catch (InterruptedException e) {
// no action needed
}
}
}
}

public class MultiThreadWithSleep {


public static void main(String[] args) {
MyThread t1 = new MyThread(1, 5); // prints 1–5
MyThread t2 = new MyThread(6, 10); // prints 6–10

[Link]();
[Link]();
}
}

. class TestJoinMethod1 extends Thread{


. public void run(){
. for(int i=1;i<=5;i++){
. try{
. [Link](500);
. }catch(Exception e){[Link](e);}
. [Link](i);
. }
. }
. public static void main(String args[]){
. TestJoinMethod1 t1=new TestJoinMethod1();
. TestJoinMethod1 t2=new TestJoinMethod1();
. TestJoinMethod1 t3=new TestJoinMethod1();
. [Link]();
. try{
. [Link]();
. }catch(Exception e){[Link](e);}
.
. [Link]();
. [Link]();
. }
. }
Feature sleep() join()
Belongs to Static method of Thread Instance method of Thread
Who is Calling thread (waits for another
Current thread
affected? thread)
Wait for another thread to
Purpose Pause execution for fixed time
complete
Fixed duration (milliseconds,
Time Control Until thread finishes (or timeout)
nanoseconds)
Releases
❌ No ❌ No
Locks?
Throws
InterruptedException InterruptedException
Exception
Delay between prints, timers, Ensure thread order (e.g., t1
Usage Example
simulation before t2)

4) Using the Thread Class: Thread(Runnable r, String name)


Observe the following program.
FileName: [Link]

. public class MyThread2 implements Runnable


. {
. public void run()
. {
. [Link]("Now the thread is running ...");
. }
.
. // main method
. public static void main(String argvs[])
. {
. // creating an object of the class MyThread2
. Runnable r1 = new MyThread2();
.
. // creating an object of the class Thread using Thread(Runnable r, String name)
. Thread th1 = new Thread(r1, "My new thread");
.
. // the start() method moves the thread to the active state
. [Link]();
.
. // getting the thread name by invoking the getName() method
. String str = [Link]();
. [Link](str);
. }
. }
Output:
My new thread
Now the thread is running ...

Basic Usage of [Link]() Method


Here's a simple example of using [Link]():
File Name: [Link]

. public class SleepExample {


. public static void main(String[] args) {
. [Link]("Start");
. try {
. [Link](2000); // Pause for 2000 milliseconds (2 seconds)
. } catch (InterruptedException e) {
. [Link]("Thread interrupted");
. }
. [Link]("End");
. }
. }
Output:
Start
End
In this example, the main thread prints "Start", pauses for 2 seconds, and then prints
"End".
Handling InterruptedException
File Name: [Link]

. public class InterruptHandling {


. public static void main(String[] args) {
. Thread thread = new Thread(() -> {
. try {
. [Link]("Thread will sleep for 5 seconds.");
. [Link](5000);
. [Link]("Thread woke up after sleep.");
. } catch (InterruptedException e) {
. [Link]("Thread was interrupted during sleep.");
. }
. });
. [Link]();
. try {
. [Link](2000); // Main thread sleeps for 2 seconds
. [Link](); // Interrupt the sleeping thread
. } catch (InterruptedException e) {
. [Link]();
. }
. }
. }
Output:
Thread will sleep for 5 seconds.
Thread was interrupted during sleep.

Example of the sleep() method in Java : on the custom thread


The following example shows how one can use the sleep() method on the custom
thread.
FileName: [Link]

. class TestSleepMethod1 extends Thread{


. public void run(){
. for(int i=1;i<5;i++){
. // the thread will sleep for the 500 milli seconds
. try{[Link](500);}catch(InterruptedException e){[Link](e);}
. [Link](i);
. }
. }
. public static void main(String args[]){
. TestSleepMethod1 t1=new TestSleepMethod1();
. TestSleepMethod1 t2=new TestSleepMethod1();
.
. [Link]();
. [Link]();
. }
. }
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for
the specified time, the thread scheduler picks up another thread and so on.
Example of the sleep() Method in Java : on the main thread
FileName: [Link]
. // important import statements
. import [Link];
. import [Link].*;
.
.
. public class TestSleepMethod2
. {
. // main method
. public static void main(String argvs[])
. {
.
. try {
. for (int j = 0; j < 5; j++)
. {
.
. // The main thread sleeps for the 1000 milliseconds, which is 1 sec
. // whenever the loop runs
. [Link](1000);
.
. // displaying the value of the variable
. [Link](j);
. }
. }
. catch (Exception expn)
. {
. // catching the exception
. [Link](expn);
. }
. }
. }
Output:
0
1
2
3
4

Can we start a thread twice


No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.
Let's understand it by the example given below:

. public class TestThreadTwice1 extends Thread{


. public void run(){
. [Link]("running...");
. }
. public static void main(String args[]){
. TestThreadTwice1 t1=new TestThreadTwice1();
. [Link]();
. [Link]();
. }
. }
Test it Now
Output:
running
Exception in thread "main" [Link]

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY


is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
FileName: [Link]

class MyThread extends Thread {


public MyThread(String name) {
super(name); // set thread name
}

public void run() {


for (int i = 1; i <= 5; i++) {
[Link](getName() + " running with priority " +
getPriority());
try {
[Link](300); // pause for readability
} catch (InterruptedException e) {
// do nothing
}
}
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
MyThread t1 = new MyThread("Low Priority Thread");
MyThread t2 = new MyThread("Normal Priority Thread");
MyThread t3 = new MyThread("High Priority Thread");

[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5 (default)
[Link](Thread.MAX_PRIORITY); // 10

[Link]();
[Link]();
[Link]();
}
}

Points to remember for Daemon Thread in Java


 It provides services to user threads for background supporting tasks. It has no
role in life than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?


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.
Methods for Java Daemon thread by Thread class

No. Method Description

1) public void setDaemon(boolean is used to mark the current thread


status) as daemon thread or user thread.

2) public boolean isDaemon() is used to check that current is


daemon.
The [Link] class provides two methods for java daemon thread.
Simple example of Daemon thread in java
File: [Link]

. public class TestDaemonThread1 extends Thread{


. public void run(){
. if([Link]().isDaemon()){//checking for daemon thread
. [Link]("daemon thread work");
. }
. else{
. [Link]("user thread work");
. }
. }
. public static void main(String[] args){
. TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
. TestDaemonThread1 t2=new TestDaemonThread1();
. TestDaemonThread1 t3=new TestDaemonThread1();
.
. [Link](true);//now t1 is daemon thread
.
. [Link]();//starting threads
. [Link]();
. [Link]();
. }
. }
Test it Now
Output:
daemon thread work
user thread work
user thread work
Note: If you want to make a user thread as Daemon, it must not be started
otherwise it will throw IllegalThreadStateException.
File: [Link]

. class TestDaemonThread2 extends Thread{


. public void run(){
. [Link]("Name: "+[Link]().getName());
. [Link]("Daemon: "+[Link]().isDaemon());
. }
.
. public static void main(String[] args){
. TestDaemonThread2 t1=new TestDaemonThread2();
. TestDaemonThread2 t2=new TestDaemonThread2();
. [Link]();
. [Link](true);//will throw exception here
. [Link]();
. }
. }
Test it Now
Output:
exception in thread main: [Link]

Daemon Thread in Java

 It provides services to user threads for background supporting


tasks. It has no role in life than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.
. public class TestDaemonThread1 extends Thread{
. public void run(){
. if([Link]().isDaemon()){//checking for daemon thre
ad
. [Link]("daemon thread work");
. }
. else{
. [Link]("user thread work");
. }
. }
. public static void main(String[] args){
. TestDaemonThread1 t1=new TestDaemonThread1();//creating thr
ead
. TestDaemonThread1 t2=new TestDaemonThread1();
. TestDaemonThread1 t3=new TestDaemonThread1();
.
. [Link](true);//now t1 is daemon thread
.
. [Link]();//starting threads
. [Link]();
. [Link]();
. }
. }

Synchronization in Java
Synchronization in Java is a critical concept in concurrent programming that ensures
multiple threads can interact with shared resources safely. In a nutshell,
synchronization prevents race conditions, where the outcome of operations depends
on the timing of thread execution. It is the capability to control the access of multiple
threads to any shared resource. Synchronization is a better option where we want to
allow only one thread to access the shared resource.
Understanding Threads and Shared Resources
Thread represents an independent path of execution within a program. When multiple
threads access shared resources concurrently, problems may arise due to
unpredictable interleaving of operations. Consider a scenario where two threads
increment a shared variable concurrently:

. class Counter {
. private int count = 0;
. public void increment() {
. count++;
. }
. }
If two threads execute increment() simultaneously, they might read the current value
of count, increment it, and write it back concurrently. This can result in lost updates or
incorrect final values due to race conditions.
Introducing Synchronization
Synchronization in Java tackles these problems through the capacity of a single thread
to have exclusive access to either a synchronized block of code or a synchronized
method associated with an object in question at a time. There are two primary
mechanisms for synchronization in Java: synchronized methods and synchronized
blocks.
Synchronized Methods
Example: Synchronized Counter

. class SynchronizedCounter {
. private int count = 0;
. public synchronized void increment() {
. count++;
. }
. public synchronized int getCount() {
. return count;
. }
. }
With this modification, concurrent calls to increment() or getCount() will be
synchronized, preventing race conditions.
Synchronized Blocks
Synchronized block provides exclusive access to shared resources, and only one
thread is allowed to execute it in the same time frame. It's structured as follows:

. synchronized (object) {
. // Synchronized code block
. }
Why use Synchronization?
The synchronization is mainly used to
1. thread interference, and
2. Consistency problem

Types of Synchronization
There are the following 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 in Java: mutual exclusive and inter-
thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in Java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every
object has a lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
From Java 5 the package [Link] contains several lock
implementations.
Understanding the Problem without Synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the
example:
Example

. class Table {
. // Method to print the table, not synchronized
. void printTable(int n) {
. for(int i = 1; i <= 5; i++) {
. // Print the multiplication result
. [Link](n * i);
. try {
. // Pause execution for 400 milliseconds
. [Link](400);
. } catch(Exception e) {
. // Handle any exceptions
. [Link](e);
. }
. }
. }
. }
. class MyThread1 extends Thread {
. Table t;
. // Constructor to initialize Table object
. MyThread1(Table t) {
. this.t = t;
. }
. // Run method to execute thread
. public void run() {
. // Call printTable method with argument 5
. [Link](5);
. }
. }
. class MyThread2 extends Thread {
. Table t;
. // Constructor to initialize Table object
. MyThread2(Table t) {
. this.t = t;
. }
. // Run method to execute thread
. public void run() {
. // Call printTable method with argument 100
. [Link](100);
. }
. }
. public class Main {
. public static void main(String args[]) {
. // Create a Table object
. Table obj = new Table();
. // Create MyThread1 and MyThread2 objects with the same Table object
. MyThread1 t1 = new MyThread1(obj);
. MyThread2 t2 = new MyThread2(obj);
. // Start both threads
. [Link]();
. [Link]();
. }
. }
Output:
5
100
10
200
15
300
20
400
25
500
Java Synchronized Method
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 thread completes its task.
Example

. class Table {
. // Synchronized method to print the table
. synchronized void printTable(int n) {
. for(int i = 1; i <= 5; i++) {
. // Print the multiplication result
. [Link](n * i);
. try {
. // Pause execution for 400 milliseconds
. [Link](400);
. } catch(Exception e) {
. // Handle any exceptions
. [Link](e);
. }
. }
. }
. }
. class MyThread1 extends Thread {
. Table t;
. // Constructor to initialize Table object
. MyThread1(Table t) {
. this.t = t;
. }
. // Run method to execute thread
. public void run() {
. // Call synchronized method printTable with argument 5
. [Link](5);
. }
. }
. class MyThread2 extends Thread {
. Table t;
. // Constructor to initialize Table object
. MyThread2(Table t) {
. this.t = t;
. }
. // Run method to execute thread
. public void run() {
. // Call synchronized method printTable with argument 100
. [Link](100);
. }
. }
. public class Main {
. public static void main(String args[]) {
. // Create a Table object
. Table obj = new Table();
. // Create MyThread1 and MyThread2 objects with the same Table object
. MyThread1 t1 = new MyThread1(obj);
. MyThread2 t2 = new MyThread2(obj);
. // Start both threads
. [Link]();
. [Link]();
. }
. }
Output:
5
10
15
20
25
100
200
300
400
500
Example of Synchronized Method by Using Anonymous Class
In this program, we have created the two threads by using the anonymous class, so
less coding is required.
Example

. // Program of synchronized method by using anonymous class


. class Table {
. // Synchronized method to print the table
. synchronized void printTable(int n) {
. for(int i = 1; i <= 5; i++) {
. // Print the multiplication result
. [Link](n * i);
. try {
. // Pause execution for 400 milliseconds
. [Link](400);
. } catch(Exception e) {
. // Handle any exceptions
. [Link](e);
. }
. }
. }
. }
. public class Main {
. public static void main(String args[]) {
. // Create a Table object
. final Table obj = new Table(); // Only one object
. // Create thread t1 using anonymous class
. Thread t1 = new Thread() {
. public void run() {
. // Call synchronized method printTable with argument 5
. [Link](5);
. }
. };
. // Create thread t2 using anonymous class
. Thread t2 = new Thread() {
. public void run() {
. // Call synchronized method printTable with argument 100
. [Link](100);
. }
. };
. // Start both threads
. [Link]();
. [Link]();
. }
. }
Output:
5
10
15
20
25
100
200
300
400
500

Thread Safety

Synchronization ensures that only one thread can access a shared resource (like a
method or a block of code) at a time.

This prevents data inconsistency and race conditions.

Data Consistency

Since only one thread modifies the shared resource at a time, synchronization helps
maintain consistent data.

Predictable Execution

By controlling access to critical sections, synchronization ensures predictable results,


even in a multithreaded environment.

Avoids Race Conditions

Synchronization eliminates situations where multiple threads compete to modify the


same resource simultaneously.

Reliability in Multithreaded Programs

It makes complex multithreaded applications more reliable and stable, since the
execution order of critical operations is controlled.

Coordination Between Threads


Synchronization helps in proper communication between threads (e.g., using wait()
and notify()), ensuring smooth coordination.

Ease of Maintenance

Although it may add some overhead, synchronized code is easier to maintain and
debug compared to unsynchronized code with unpredictable behavior

Inter-thread Communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
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 [Link] is implemented by following methods
of Object class:
o wait()
o notify()
o notifyAll()

1) wait() method

The 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 It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException

2) notify() method
The 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()


Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor
state of the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method


It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Let's see the important differences between wait and sleep methods.
Example of Inter Thread Communication in Java
Let's see the simple example of inter thread communication.
Example

. //Java Program to understand the use of Inter-Thread Communication


. class Customer{
. int amount=10000;
. //creating a withdraw() method which calls the wait() method
. synchronized void withdraw(int amount){
. [Link]("going to withdraw...");
.
. if([Link]<amount){
. [Link]("Less balance; waiting for deposit...");
. try{wait();}catch(Exception e){}
. }
. [Link]-=amount;
. [Link]("withdraw completed...");
. }
. //creating a deposit() method with calls the notify() method
. synchronized void deposit(int amount){
. [Link]("going to deposit...");
. [Link]+=amount;
. [Link]("deposit completed... ");
. notify();
. }
. }
. //Creating a Main class to start threads and call deposit() and withdraw()
. public class Main{
. public static void main(String args[]){
. final Customer c=new Customer();
. new Thread(){
. public void run(){[Link](15000);}
. }.start();
. new Thread(){
. public void run(){[Link](10000);}
. }.start();
. }
. }
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

You might also like