I feel guilty reaching out to StackOverflow for help in school, but I've exhausted my resources and cannot figure this one out for the life of me. For one of my classes I am required to understand how to construct and properly use Semaphores in Java. One of the exercises has the following code:
import java.lang.Thread;
import java.util.concurrent.*;
public class ThreadSync
{
private static boolean runFlag = true;
public static void main( String[] args ) {
Runnable[] tasks = new Runnable[37];
Thread[] threads = new Thread[37];
// create 10 digit threads
for (int d=0; d<10; d++) {
tasks[d] = new PrintDigit(d);
threads[d] = new Thread( tasks[d] );
threads[d].start();
}
// create 26 letter threads
for (int d=0; d<26; d++) {
tasks[d+10] = new PrintLetter((char)('A'+d));
threads[d+10] = new Thread( tasks[d+10] );
threads[d+10].start();
}
// create a coordinator thread
tasks[36] = new PrintSlashes();
threads[36] = new Thread( tasks[36] );
threads[36].start();
// Let the threads to run for a period of time
try {
Thread.sleep(50);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
runFlag = false;
// Interrupt the threads
for (int i=0; i<37; i++) threads[i].interrupt();
}
public static class PrintDigit implements Runnable
{
int digit;
public PrintDigit(int d) { digit=d; }
public void run(){
while (runFlag) {
System.out.printf( "%d\n", digit);
}
}
}
public static class PrintLetter implements Runnable
{
char letter;
public PrintLetter(char c) { letter=c; }
public void run(){
while (runFlag) {
System.out.printf( "%c\n", letter);
}
}
}
public static class PrintSlashes implements Runnable
{
public void run(){
while (runFlag) {
System.out.printf( "%c\n", '/');
System.out.printf( "%c\n", '\\');
}
}
}
}
I need to modify the code, only by adding "semaphore-related statements" such that the program repeatedly prints out a '/' followed by three digits, then a '\' followed by two letters.
The example they give is as follows:
/156\BA/376\YZ/654\JK/257\HG/445\DD…
Any help would be greatly appreciated. I'm usually pretty good at learning on my own but these threads have my head spinning! Thanks!