I\'m trying to understand thread basics, and as a first example I create two thread that write a String on the stdout. As I know the scheduler allows to execute the threads
Here is a version that uses Semaphore
objects to accomplish synchronization:
import java.util.concurrent.*;
public class Main {
@FunctionalInterface
public interface QuadFunction {
public R apply(T t, U u, V v, W w);
}
public static void main(String[] args) {
ExecutorService svc = Executors.newFixedThreadPool(2);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Terminating...");
svc.shutdownNow();
try { svc.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); }
catch(InterruptedException e) {};
}));
var sem1 = new Semaphore(1);
var sem2 = new Semaphore(0);
QuadFunction fun =
(name, action, s1, s2) ->
(Runnable) () -> {
try {
while (true) {
s1.acquire();
System.out.format("%s %s\n", name, action);
Thread.sleep(500);
s2.release(1);
}
} catch (InterruptedException e) {}
s2.release(1);
System.out.format("==> %s shutdown\n", name);
};
svc.execute(fun.apply("T1", "ping", sem1, sem2));
svc.execute(fun.apply("T2", "pong", sem2, sem1));
}
}