Created
May 22, 2017 21:17
-
-
Save ggdio/3fb678bfe1b96f94ac21f86220daa8a8 to your computer and use it in GitHub Desktop.
Testing the Semaphore execution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.ggdio.util.concurrent.test; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class SemaphoreTest { | |
private static Semaphore semaphore = new Semaphore(); | |
private static AtomicInteger count = new AtomicInteger(0); | |
public static void main(String[] args) { | |
ExecutorService threadPool = Executors.newFixedThreadPool(5); | |
threadPool.submit(new Process()); | |
threadPool.submit(new Process()); | |
threadPool.submit(new Process()); | |
threadPool.submit(new Process()); | |
threadPool.submit(new Process()); | |
Executors.newSingleThreadExecutor().execute(new ProcessManager()); | |
} | |
private static class ProcessManager implements Runnable { | |
@Override | |
public void run() { | |
try { | |
while(true) { | |
Thread.sleep(10000); | |
System.err.println("ThreadManager[name=" + Thread.currentThread().getName() + "] Setting red signal."); | |
semaphore.setRedSignal(); | |
Thread.sleep(10000); | |
System.err.println("ThreadManager[name=" + Thread.currentThread().getName() + "] Setting green signal."); | |
semaphore.setGreenSignal(); | |
} | |
} catch (InterruptedException e) { | |
System.out.println("ThreadManager[name=" + Thread.currentThread().getName() + "] Finished."); | |
} | |
} | |
} | |
private static class Process implements Runnable { | |
@Override | |
public void run() { | |
try { | |
while(true) { | |
Sysout.print("Thread[name=" + Thread.currentThread().getName() + "] Running for the #" + count.incrementAndGet() + " time."); | |
Thread.sleep(new Long(Math.round((Math.random() * 10000)))); | |
} | |
} catch (InterruptedException e) { | |
System.out.println("Thread[name=" + Thread.currentThread().getName() + "] Finished."); | |
} | |
} | |
} | |
private static class Sysout { | |
public static void print(String message) { | |
semaphore.proceed(); // If it's red, then it will await for green signal | |
System.out.println(message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment