0% found this document useful (0 votes)
8 views

PPTS

The document discusses multithreading in Java, explaining that it allows multiple threads to execute simultaneously, which is more efficient than multiprocessing due to shared memory usage. It details the advantages of multithreading, the lifecycle of threads, and how to create and manage threads using the Thread class and Runnable interface. Additionally, it covers thread scheduling, priorities, synchronization, and methods like sleep(), join(), and yield().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

PPTS

The document discusses multithreading in Java, explaining that it allows multiple threads to execute simultaneously, which is more efficient than multiprocessing due to shared memory usage. It details the advantages of multithreading, the lifecycle of threads, and how to create and manage threads using the Thread class and Runnable interface. Additionally, it covers thread scheduling, priorities, synchronization, and methods like sleep(), join(), and yield().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

Department of CSEH

ADVANCED OBJECT ORIENTED


PROGRAMMING
23CS2103R
Topic: Multithreading in Java

CO- 3

CREATED BY K. VICTOR BABU


Multithreading in Java

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


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.

CREATED BY K. VICTOR BABU


Advantages of Java Multithreading

1) It doesn't block the user because threads are independent


and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves


time.

3) Threads are independent, so it doesn't affect other threads


if an exception occurs in a single thread.

CREATED BY K. VICTOR BABU


Multitasking

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
What is Thread in java

A thread is a lightweight subprocess, the smallest unit of


processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it


doesn't affect other threads. It uses a shared memory area.

CREATED BY K. VICTOR BABU


Java Thread class

Java Threads | How to create a thread in Java


There are two ways to create a thread:

1.By extending Thread class


2.By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to


create and perform operations on a thread. Thread
class extends Object class and implements Runnable
interface.
Commonly used Constructors of Thread class:
•Thread()
•Thread(String name)
•Thread(Runnable r)
•Thread(Runnable r, String name)

CREATED BY K. VICTOR BABU


Commonly used methods of Thread class:
1.public void run(): is used to perform action for
a thread.
2.public void start(): starts the execution of the
thread.JVM 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
CREATED BY K. VICTOR BABU the priority of the thread.
1.public Thread currentThread(): returns the
reference of currently executing thread.
2.public int getId(): returns the id of the thread.
3.public Thread.State getState(): returns the
state of the thread.
4.public boolean isAlive(): tests if the thread is
alive.
5.public void yield(): causes the currently
executing thread object to temporarily pause and
allow other threads to execute.
6.public void suspend(): is used to suspend the
thread(depricated).
7.public void resume(): is used to resume the
suspended thread(depricated).
8.public void stop(): is used to stop the
thread(depricated).
9.public boolean isDaemon(): tests if the thread
is a daemon thread.
10.public void setDaemon(boolean b): marks
the thread as daemon or user thread.
11.public void interrupt(): interrupts the thread.
12.public boolean isInterrupted(): tests if the
thread has been interrupted.
CREATED BY K. VICTOR BABU 13.public static boolean interrupted(): tests if
Runnable interface:
The Runnable interface should be implemented by
any class whose instances are intended to be
executed by a thread. Runnable interface have
only one method named run().
1.public void run(): is used to perform action for
a thread.

Starting a thread:

The start() method of Thread class is used to


start a newly created thread. It performs the
following tasks:
•A new thread starts(with new callstack).
•The thread moves from New state to the Runnable
state.
•When the thread gets a chance to execute, its
target run() method will run.

CREATED BY K. VICTOR BABU


class MyThread extends Thread {
public void run() {
// Code to be executed in the thread
}
}

// Create and start a thread


MyThread thread = new MyThread();
thread.start();

CREATED BY K. VICTOR BABU


class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the thread
}
}

// Create a Runnable and pass it to a Thread


Thread thread = new Thread(new MyRunnable());
thread.start();

CREATED BY K. VICTOR BABU


1.class Multi extends Thread{
2.public void run(){
3.System.out.println("thread is running...");
4.}
5.public static void main(String args[]){
6.Multi t1=new Multi();
7.t1.start();
8. }
9.}

CREATED BY K. VICTOR BABU


Java Thread Example by implementing Runnable
interface
1.class Multi3 implements Runnable{
2.public void run(){
3.System.out.println("thread is running...");
4.}
5.
6.public static void main(String args[]){
7.Multi3 m1=new Multi3();
8.Thread t1 =new Thread(m1); // Using the constructor Threa
d(Runnable r)
9.t1.start();
10. }
11.}

CREATED BY K. VICTOR BABU


Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new


threads using the constructors defined above.
FileName: MyThread1.java
1.public class MyThread1
2.{
3.// Main method
4.public static void main(String argvs[])
5.{
6.// creating an object of the Thread class using the co
nstructor Thread(String name)
7.Thread t= new Thread("My first thread");
8.
9.// the start() method moves the thread to the active
state
10.t.start();
11.// getting the thread name by invoking the getNam
e() method
12.String str = t.getName();
13.System.out.println(str);
14.}
CREATED BY K. VICTOR BABU
Using the Thread Class: Thread(Runnable r, String
name)

1.public class MyThread2 implements Runnable 1./ creating an object of the class Thread using T
hread(Runnable r, String name)
2.{ 2.Thread th1 = new Thread(r1, "My new thread")
3.public void run() ;
4.{ 3.
5.System.out.println("Now the thread is running4.//..."
the start() method moves the thread to the a
); ctive state
6.} 5.th1.start();
7. 6.
8.// main method 7.// getting the thread name by invoking the getN
9.public static void main(String argvs[]) ame() method
10.{ 8.String str = th1.getName();
11.// creating an object of the class MyThread29.System.out.println(str);
12.Runnable r1 = new MyThread2(); 10.}
11.}

CREATED BY K. VICTOR BABU


Life cycle of a Thread (Thread
States)

CREATED BY K. VICTOR BABU


Thread Lifecycle

Waiting /
Blocked

Ready /
Running
Runnable
If Thread Scheduler
.
allocates CPU
t.start() If run() method
completes
Dead /
New
t = new Terminat
MyThread() e
9/3/20XX Presentation Title 18
CREATED BY K. VICTOR BABU
public class Mythread extends Thread{ public class Demo {
public void run()
{ public static void main(String[] args) {
for(int i=1;i<=10;i++) // TODO Auto-generated method stub
Mythread t=new Mythread();
System.out.println("Child Thred"); t.start();
} for(int i=1;i<=10;i++)
System.out.println("MAIN Thred");
}

CREATED BY K. VICTOR BABU


public class Mythread extends Thread{ public class Demo {
public void run()
{ public static void main(String[] args) {
for(int i=1;i<=10;i++) // TODO Auto-generated method stub
Mythread t=new Mythread();
System.out.println("Child Thred"); t.run();
} for(int i=1;i<=10;i++)
System.out.println("MAIN Thred");
}

CREATED BY K. VICTOR BABU


Note
Case 1 : Importance of Thread class start() method
start(){
1.Register the thread with Thread Scheduler.
2.Perform all the mandatory activities.
3.Invoke run() method
}

CREATED BY K. VICTOR BABU


Note
Case 2 : Starting Thread twice will raise IllegalThreadStateException.
t.start();
t.start();

CREATED BY K. VICTOR BABU


Overload Run method:

public class Mythread extends Thread{


public void run()
{
System.out.println(“no arg");
}

public void run(int i)


{
System.out.println(“with arg");
}
}

CREATED BY K. VICTOR BABU


public class Demo {

public static void main(String[] args) {


// TODO Auto-generated method stub
Mythread t=new Mythread();
t.start();
t.run(7);

CREATED BY K. VICTOR BABU


Overload Start Method:

public class Mythread extends Thread{


public void start()
{
System.out.println(“start method");
}

public void run()


{
System.out.println(“run method");
}
}

CREATED BY K. VICTOR BABU


public class Demo {

public static void main(String[] args) {


// TODO Auto-generated method stub
Mythread t=new Mythread();
t.start();
System.out.println(“Main method");

CREATED BY K. VICTOR BABU


Thread Scheduler in Java

A component of Java that decides which thread to run or execute and which thread to

wait is called a thread scheduler in Java. In Java, a thread is only chosen by a

thread scheduler if it is in the runnable state. However, if there is more than one

thread in the runnable state, it is up to the thread scheduler to pick one of the

threads and ignore the other ones. There are some criteria that decide which thread

will execute first. There are two factors for scheduling a thread i.e. Priority and Time

of arrival.

CREATED BY K. VICTOR BABU


Priority: Priority of each thread lies between 1 to 10. If a thread has a higher
priority, it means that thread has got a better chance of getting picked up by the
thread scheduler.

Time of Arrival: Suppose two threads of the same priority enter the runnable
state, then priority cannot be the factor to pick a thread from these two threads. In
such a case, arrival time of thread is considered by the thread scheduler. A
thread that arrived first gets the preference over the other threads.

CREATED BY K. VICTOR BABU


Thread.sleep() in Java with Examples

The sleep() Method Syntax:

1.public static void sleep(long mls) throws InterruptedE


xception
2.public static void sleep(long mls, int n) throws Interru
ptedException
Parameters:
The following are the parameters used in the sleep() method.

mls: The time in milliseconds is represented by the parameter mls. The


duration for which the thread will sleep is given by the method sleep().

n: It shows the additional time up to which the programmer or developer


wants the thread to be in the sleeping state. The range of n is from 0 to
999999.

CREATED BY K. VICTOR BABU


1.class TestSleepMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. // the thread will sleep for the 500 milli seconds

5. try{Thread.sleep(500);}catch(InterruptedExc
eption e){System.out.println(e);}
6. System.out.println(i);
7. }
8. }
9. public static void main(String args[]){
10. TestSleepMethod1 t1=new TestSleepMethod1(
);
11. TestSleepMethod1 t2=new TestSleepMethod1(
);
12.
13. t1.start();
14. t2.start();
15. }
16.}
CREATED BY K. VICTOR BABU
Important Points to Remember About the Sleep()
Method

Whenever the Thread.sleep() methods execute, it always halts the


execution of the current thread.

Whenever another thread does interruption while the current thread is


already in the sleep mode, then the InterruptedException is thrown.

If the system that is executing the threads is busy, then the actual
sleeping time of the thread is generally more as compared to the time
passed in arguments. However, if the system executing the sleep()
method has less load, then the actual sleeping time of the thread is
almost equal to the time passed in the argument.

CREATED BY K. VICTOR BABU


Thread Priorities
• Thread priorities are used by the thread scheduler to decide when
each thread should be allowed to run.

CREATED BY K. VICTOR BABU


Thread Priorities
• Every thread in java has some priority.
• Default Priority generated by JVM

• Custom Priority

• Valid range of thread priorities 1-10.

• 1 – MIN_PRIORITY

• 10 – MAX_PRIORITY

• 5 – NORM_PRIORITY

CREATED BY K. VICTOR BABU


Thread Priorities
• Thread Scheduler uses priorities to allocate Processor.

• getPriority()

• setPriority(int level)

• Default priority for main thread is 5. (default priority will be inherited


from parent to child)

CREATED BY K. VICTOR BABU


The join() method allows one thread to wait for the completion of another thread.

In Java, the yield() method is a static method of the Thread class. It's used to pause the execution of the
currently executing thread temporarily, allowing other threads of the same priority to execute

However, it's important to note that the yield() method is just a suggestion to the scheduler; it's not
guaranteed that the thread will yield the CPU.

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
Synchronization in Java

Synchronization in Java is the capability to control the access of multiple


threads to any shared resource.
Java Synchronization is a better option where we want to allow only one
thread to access the shared resource.

Why use Synchronization?


The synchronization is mainly used to
1.To prevent thread interference.
2.To prevent consistency problem.

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
1.class MyThread2 extends Thread{ 1.public class TestSynchronization2{
2.Table t; 2.public static void main(String args[]){
3.MyThread2(Table t){ 3.Table obj = new Table();//only one object
4.this.t=t; 4.MyThread1 t1=new MyThread1(obj);
5.} 5.MyThread2 t2=new MyThread2(obj);
6.public void run(){ 6.t1.start();
7.t.printTable(100); 7.t2.start();
8.} 8.}
9.} 9.}

CREATED BY K. VICTOR BABU


Types of Synchronization
There are two types of synchronization
1.Process Synchronization
2.Thread Synchronization

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

3.Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
4.Cooperation (Inter-thread communication in java)

CREATED BY K. VICTOR BABU


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

In Java, mutual exclusion is typically implemented using locks. A lock is an object that can be
acquired by a thread. Once a thread has acquired a lock, no other thread can acquire it until
the first thread releases it.

CREATED BY K. VICTOR BABU


1.class Table{
2.void printTable(int n){//
method not synchronized 1.Class MyThread1 extends Thread{
3. for(int i=1;i<=5;i++){ 2.Table t;
4. System.out.println(n*i); 3.MyThread1(Table t){
5. try{ 4.this.t=t;
6. Thread.sleep(400); 5.}
7. 6.public void run(){
}catch(Exception e){System.out.println(e);}
8. } 7.t.printTable(5);
9. 8.}
10. } 9.
11.} 10.}

CREATED BY K. VICTOR BABU


1.class MyThread2 extends Thread{
2.Table t; 1.class TestSynchronization1{
3.MyThread2(Table t){ 2.public static void main(String args[]){
4.this.t=t; 3.Table obj = new Table();//only one object
5.} 4.MyThread1 t1=new MyThread1(obj);
6.public void run(){ 5.MyThread2 t2=new MyThread2(obj);
7.t.printTable(100); 6.t1.start();
8.} 7.t2.start();
9.} 8.}
9.}

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
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.

CREATED BY K. VICTOR BABU


1.class Table{
1.class MyThread1 extends Thread{
2. synchronized void printTable(int n){//
2.Table t;
synchronized method
3.MyThread1(Table t){
3. for(int i=1;i<=5;i++){
4.this.t=t;
4. System.out.println(n*i);
5.}
5. try{
6.public void run(){
6. Thread.sleep(400);
7.t.printTable(5);
7. }catch(Exception e){System.out.println(e);}
8.}
8. }
9.
9.
10.}
10. }
11.}

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
Example of synchronized method by using
annonymous class
1./
Program of synchronized method by using annony
mous class
2.class Table{
3. synchronized void printTable(int n){//
synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12.}

CREATED BY K. VICTOR BABU


1.public class TestSynchronization3{
2.public static void main(String args[]){
3.final Table obj = new Table();//only one object
4.
5.Thread t1=new Thread(){
6.public void run(){
7.obj.printTable(5);
8.}
9.};
10.Thread t2=new Thread(){
11.public void run(){
12.obj.printTable(100);
13.}
14.};
15.
16.t1.start();
17.t2.start();
18.}
19.}

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
Synchronized Block in Java

Synchronized block can be used to perform synchronization on any specific resource of


the method.
Suppose we have 50 lines of code in our method, but we want to synchronize only 5
lines, in such cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will work same as
the synchronized method.

Points to Remember

•Synchronized block is used to lock an object for any shared resource.

•Scope of synchronized block is smaller than the method.

•A Java synchronized block doesn't allow more than one JVM, to provide access control
to a shared resource.

•The system performance may degrade because of the slower working of synchronized
keyword.

•Java synchronized block is more efficient than Java synchronized method.


CREATED BY K. VICTOR BABU
Syntax
1.synchronized (object reference expression) {

2. //code block
3.}

1.class Table
2.{
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e)
{System.out.println(e);}
10. }
11. }
12. }//end of the method
13.}

CREATED BY K. VICTOR BABU


1.class MyThread1 extends Thread{
2.Table t; 1.class MyThread2 extends Thread{
3.MyThread1(Table t){ 2.Table t;
4.this.t=t; 3.MyThread2(Table t){
5.} 4.this.t=t;
6.public void run(){ 5.}
7.t.printTable(5); 6.public void run(){
8.} 7.t.printTable(100);
9. 8.}
10.} 9.}

CREATED BY K. VICTOR BABU


1.public class TestSynchronizedBlock1{
2.public static void main(String args[]){
3.Table obj = new Table();//only one object
4.MyThread1 t1=new MyThread1(obj);
5.MyThread2 t2=new MyThread2(obj);
6.t1.start();
7.t2.start();
8.}
9.}

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
Static Synchronization

CREATED BY K. VICTOR BABU


Static Synchronization
If you make any static method as synchronized,
the lock will be on the class not on object

CREATED BY K. VICTOR BABU


Problem without static synchronization
Suppose there are two objects of a shared class (e.g. Table) named object1 and
object2. In case of synchronized method and synchronized block there cannot
be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to
a common object that have a single lock. But there can be interference
between t1 and t3 or t2 and t4 because t1 acquires another lock and t3
acquires another lock. We don't want interference between t1 and t3 or t2 and
t4. Static synchronization solves this problem.

CREATED BY K. VICTOR BABU


Static Synchronization

CREATED BY K. VICTOR BABU


Static Synchronization

CREATED BY K. VICTOR BABU


Static Synchronization

CREATED BY K. VICTOR BABU


Deadlock in Java

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.

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
More Complicated Deadlocks

A deadlock may also include more than two threads. The reason is that it can be
difficult to detect a deadlock. Here is an example in which four threads have
deadlocked:
Thread 1 locks A, waits for B

Thread 2 locks B, waits for C

Thread 3 locks C, waits for D

Thread 4 locks D, waits for A

Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread 4, and thread 4 waits for
thread 1.

How to avoid deadlock?

A solution for a problem is found at its roots. In deadlock it is the pattern of accessing the resources A and
B, is the main issue. To solve the issue we will have to simply re-order the statements where the code is
accessing shared resources.

CREATED BY K. VICTOR BABU


How to Avoid Deadlock in Java?
Deadlocks cannot be completely resolved. But we can avoid them by following basic
rules mentioned below:

1.Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the
main reason for a deadlock condition. It normally happens when you give locks to
multiple threads.

2.Avoid Unnecessary Locks: The locks should be given to the important threads.
Giving locks to the unnecessary threads that cause the deadlock condition.

3.Using Thread Join: A deadlock usually happens when one thread is waiting for the
other to finish. In this case, we can use join with a maximum time that a thread will
take.

CREATED BY K. VICTOR BABU


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 executed. It is implemented by following methods of Object class:

•wait()
•notify()
•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.

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
2) notify() method

The notify() method wakes up a single thread that is waiting on this object's monitor.

Syntax:

1.public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.


Syntax:
2.public final void notifyAll()

CREATED BY K. VICTOR BABU


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.

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

CREATED BY K. VICTOR BABU


illustrating the Producer-Consumer problem using threads and
synchronization:
The ProducerConsumer class contains a buffer implemented as a LinkedList, with a capacity of 5.

The produce() method represents the producer, which continuously produces items (incrementing
integers) and adds them to the buffer. It waits if the buffer is full.

The consume() method represents the consumer, which continuously consumes items from the
buffer. It waits if the buffer is empty.

The main method initializes two threads, one for the producer and one for the consumer. They
start executing their respective methods concurrently.

Synchronization is achieved using the synchronized block, ensuring that only one thread can
access the buffer at a time.

wait() and notify() methods are used for signaling between producer and consumer threads. The
producer calls wait() when the buffer is full, and the consumer calls wait() when the buffer is
empty. They call notify() after producing or consuming an item to wake up the waiting thread.

CREATED BY K. VICTOR BABU


import java.util.LinkedList;

class ProducerConsumer {
LinkedList<Integer> buffer = new LinkedList<>();
int capacity = 5;

public void produce() throws InterruptedException {


int value = 0;
while (true) {
synchronized (this) {
while (buffer.size() == capacity)
wait();

System.out.println("Producer produced-" + value);


buffer.add(value++);

notify();

Thread.sleep(1000);
}
}
}

CREATED BY K. VICTOR BABU


public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (buffer.isEmpty())
wait();

int val = buffer.removeFirst();


System.out.println("Consumer consumed-" + val);

notify();

Thread.sleep(1000);
}
}
}
}

CREATED BY K. VICTOR BABU


public class Main { Thread t2 = new Thread(new Runnable() {
public static void main(String[] args) { public void run() {
final ProducerConsumer pc = new ProducerConsumer(); try {
pc.consume();
Thread t1 = new Thread(new Runnable() { } catch (InterruptedException e) {
public void run() { e.printStackTrace();
try { }
pc.produce(); }
} catch (InterruptedException e) { });
e.printStackTrace();
} t1.start();
} t2.start();
}); }
}

CREATED BY K. VICTOR BABU


What is a semaphore?

A Semaphore is used to limit the number of threads that want to access a shared resource. In other
words, it is a non-negative variable that is shared among the threads known as a counter. It sets the
limit of the threads. A mechanism in which a thread is waiting on a semaphore can be signaled by
other threads.

CREATED BY K. VICTOR BABU


Working of Semaphore

Semaphore controls over the shared resource through a counter variable. The counter
is a non-negative value. It contains a value either greater than 0 or equal to 0.

•If counter > 0, the thread gets permission to access the shared resource and the
counter value is decremented by 1.

•Else, the thread will be blocked until a permit can be acquired.

•When the execution of the thread is completed then there is no need for the resource
and the thread releases it. After releasing the resource, the counter
value incremented by 1.

•If another thread is waiting for acquiring a resource, the thread will acquire a permit at
that time.

•If counter = 0, the thread does not get permission to access the shared resource.

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
CREATED BY K. VICTOR BABU
Two threads, mt1 and mt2, are created with names "A" and "B" respectively.

Both threads are started using the start() method. This initiates their execution.

Thread mt1 (named "A") begins execution of its run() method. Since it's the first thread to run, it will
acquire the semaphore permit first.

Thread mt1 prints that it is waiting for a permit and then successfully acquires the permit. It enters the
critical section.

Inside the critical section, thread mt1 increments Shared.count five times, printing the current value each
time. After each increment, it sleeps for 10 milliseconds to allow thread mt2 to execute.

While thread mt1 is sleeping, thread mt2 is waiting for the semaphore permit.

After completing its execution in the critical section, thread mt1 releases the semaphore permit.

CREATED BY K. VICTOR BABU


Now, thread mt2 (named "B") gets the chance to execute. It prints that it is waiting for a permit and then
successfully acquires the permit.

Inside the critical section, thread mt2 decrements Shared.count five times, printing the current value each time.
After each decrement, it sleeps for 10 milliseconds to allow thread mt1 to execute.

After completing its execution in the critical section, thread mt2 releases the semaphore permit.

Both threads have now completed their execution.

The main thread, in the ThreadSemaphoreDemo class, waits for both mt1 and mt2 to finish using the join()
method.

Finally, after both threads have finished, the main thread prints the final value of Shared.count.

This sequence ensures that only one thread can access the critical section (manipulating Shared.count) at any
given time, ensuring the safety of the shared resource.

CREATED BY K. VICTOR BABU


Java Semaphore Class

Java provides a Semaphore class to implement the semaphore mechanism. It belongs to the
java.util.concurrent package. It implements the Serializable interface. Hence, manual
implementation is not required.

The Semaphore class provides the following two constructors:

Semaphore(int permits)
Semaphore(int permits, boolean fair)

Semaphore(int permits)

It creates a Semaphore and parses the number of permits (initial number of permits available) as
an argument. It specifies the number of threads that can share a resource at a time. The value of
permits may be negative. In such a case, a release must occur before any acquires will be
granted.

Syntax:
public Semaphore(int permits)

Semaphore(int permits, boolean fair)


It creates a Semaphore with the given number of permits and the given
CREATED BY K. VICTOR BABU fairness settings.
Syntax:

public Semaphore(int permits, boolean fair)


It parses two parameters:

permits: The value of permits may be negative. In such a case, the release must occur before any acquires will
be granted.
fair: If we set the value to true, the semaphore guarantees FIFO to the threads in the order they are requested,
false By default, all the threads that are waiting for the resource grants permit in an undefined order.

CREATED BY K. VICTOR BABU


Let's understand the above methods through a simple example.

Semaphore semaphore = new Semaphore(6); //creates a semaphore with 6 permits

semaphore.acquire(); //acquire 1 ticket

semaphore.availablePermits(); //current available permits is 5

semaphore.release(); //releases the acquire ticket and increments the permit by 1

semaphore.availablePermits(); //current available permits is 5

CREATED BY K. VICTOR BABU


CREATED BY K. VICTOR BABU
THANK YOU

Team – Advanced Object Oriented


Programming

CREATED BY K. VICTOR BABU

You might also like