Java Thread Ping Pong example

前端 未结 8 680
萌比男神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条回答
  •  攒了一身酷
    2020-12-19 18:31

    In conclusion to my discussion with Brian Agnew, I submit this code that uses java.util.concurrent.Phaser to coordinate your ping-pong threads:

    static final Phaser p = new Phaser(1);
    public static void main(String[] args) {
      t("ping");
      t("pong");
    }
    private static void t(final String msg) {
      new Thread() { public void run() {
        while (true) {
          System.out.println(msg);
          p.awaitAdvance(p.arrive()+1);
        }
      }}.start();
    }
    

    The key difference between this solution and the one you attempted to code is that your solution busy-checks a flag, thereby wasting CPU time (and energy!). The correct approach is to use blocking methods that put a thread to sleep until it is notified of the relevant event.

提交回复
热议问题