Java Thread Ping Pong example

前端 未结 8 683
萌比男神i
萌比男神i 2020-12-19 18:26

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

8条回答
  •  -上瘾入骨i
    2020-12-19 18:41

    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));
        }
    }
    

提交回复
热议问题