Write the program that does the following. Use semaphores and expand the solutio
ID: 3706824 • Letter: W
Question
Write the program that does the following. Use semaphores and expand the solution below to N threads. N is a runtime parameter, and assume N is lower than 20. The best solution will use a minimal number of semaphores.
- The main (parent) thread initializes an array of 3 integers to zero.
- The parent creates 3 children. Child i adds 1 to array[i], where i = 0, 1, 2. Order is not important.
- The parent waits for the children to finish adding, and then prints the values in the array.
- The children wait for the parent to finish printing and then repeats (adds 1 to an element of the array)
- Continues forever
Explanation / Answer
//Semaphore is used to lock a thread when it is in access.The lock can be done through acquire() and this can be //released through release()
import java.util.concurrent.*;
class Example
{
static int c = 0;
}
class MyThread extends Thread
{
Semaphore s;
String name;
public MyThread(Semaphore s, String name)
{
super(name);
this.s = s;
this.name = name;
}
public void run() {
if(this.getName().equals("Child1"))
{
System.out.println("The process of the given thread" + name);
try
{
s.acquire();//locks
for(int i=0; i < 3; i++)
{
Example.c++;
System.out.println(name + ": " + Example.c);
Thread.sleep(10);
}
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("The given thread is terminated");
s.release();
}
else if(this.getName().equals("Child2"))
{
System.out.println("The next thread enters the process" + name);
try
{
s.acquire();
for(int i=0; i < 3; i++)
{
Example.c++;
System.out.println(name + ": " + Example.c);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(name + " The given thread process is terminated");
s.release();
}
else{
{
System.out.println("The next thread is waiting for the process " + name);
try
{
s.acquire();
for(int i=0; i < 3; i++)
{
Example.c++;
System.out.println(name + ": " + Example.c);
Thread.sleep(1000);
}
} catch (InterruptedException exc) {
System.out.println(exc);
}
System.out.println(name + " The process is terminated");
s.release();
}}}}
class SemaphoreEx
{
public static void main(String args[]) throws InterruptedException
{
Semaphore s = new Semaphore(1);
MyThread m1 = new MyThread(s, "Child1");
MyThread m2 = new MyThread(s, "Child2");
MyThread m3 = new MyThread(s, "Child3");
m1.start();
m2.start();
m3.start();
m1.join();
m2.join();
m3.join();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.