Hey,
Recently been introduced to threads & came across a question involving the usage of semaphores. I'm just a bit confused as to how to use them and was wondering if anybody could shed a bit of guidance for me. I'll post the question to begin with:
Create a program using 2 seperate threads, each printing out a message when it reaches a particular part in its run method. Add a Java semaphore to the program and use it to ensure that whenever you run the program the point A is always reached before point B i.e. every time you run the program it behaves as follows:
$ java Points
Point A reached
Point B reached
Create and initialise your semaphore in the main method and pass it to each thread.
I'm unsure how & where to use this semaphore and also what parameter i'm supposed to give it.
My code so far is:
import java.util.concurrent.Semaphore; class PointA extends Thread { public PointA() { } public void run() { try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { } System.out.println("Point A reached"); } } class PointB extends Thread { public PointB() { } public void run() { try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { } System.out.println("Point B reached"); } } public class Points { public static void main(String[] args) throws InterruptedException { PointA a = new PointA(); PointB b = new PointB(); Semaphore sem = new Semaphore(0); b.start(); a.start(); b.join(); a.join(); } }
Thanks in advance for any help.