Thread Concept
Thread Concept
Assignment No - 4d
Title- Write program to synchronize threads using construct – monitor/serialize/semaphore of
Java.
Objectives –
1. To learn about threading in Linux/Unix and Java and difference between them..
2. Use of system call/library to write effective programs
Theory-
A semaphore controls access to a shared resource through the use of a counter. If the
counter is greater than zero, then access is allowed. If it is zero, then access is denied.
What the counter is counting are permits that allow access to the shared resource.
Thus, to access the resource, a thread must be granted a permit from the semaphore.
Working of semaphore : In general, to use a semaphore, the thread that wants access
to the shared resource tries to acquire a permit.
• If the semaphore’s count is greater than zero, then the thread acquires a permit,
which causes the semaphore’s count to be decremented.
• Otherwise, the thread will be blocked until a permit can be acquired.
• When the thread no longer needs an access to the shared resource, it releases the
permit, which causes the semaphore’s count to be incremented.
• If there is another thread waiting for a permit, then that thread will acquire a permit
at that time. Java provide Semaphore class in java.util.concurrent package that
implements this mechanism, so you don’t have to implement your own semaphores.
Flowchart-
Setting up semaphore with
initial value of count
Thread tries to aquire
permit(sem,release)
Thread blocked,waiting for next
Count>
0
Yes
Semaphore provide
access to shared
resource to the thread
Count
++
Program-
import java.util.concurrent.*;
public class sem extends Thread
{
public static Semaphore semaphore = new Semaphore(1);
public static void main(String args[])
throws Exception {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
sem tm = new sem();
tm.start();
t1.start();
t2.start();
}
public void run()
{
try
{
semaphore.acquire();
for(int i=0;i<=20;i=i+2)
{
System.out.println("Even: "+i);
}
semaphore.release();
}
catch(InterruptedException exc){}
}
static class Thread1 extends Thread
{
public void run()
{
try
{
semaphore.acquire();
for(int i=1;i<=21;i=i+2)
{
System.out.println("Odd: "+i);
}
semaphore.release();
}
catch(InterruptedException exc){}
}
}
static class Thread2 extends Thread
{
public void run()
{
try
{
semaphore.acquire();
for(int i=2;i<50;i++)
{
int count = 0;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==0)
System.out.println("Prime: "+i);
}
semaphore.release();
}
catch(InterruptedException exc){}
}
}
}
Output-
Conclusion:
Synchronization of multiple threads using semaphore to let threads work
synchronously to produce desirable outputs learned and implemented in Java
References:
[1] https://www.geeksforgeeks.org/multithreading-in-java