Java Thread Ping Pong example

前端 未结 8 676
萌比男神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:36

    One option is using SynchronousQueue .

    import java.util.concurrent.SynchronousQueue;
    
    public class PingPongPattern {
    
        private SynchronousQueue q = new SynchronousQueue();
        private Thread t1 = new Thread() {
    
            @Override
            public void run() {
                while (true) {
    
                    // TODO Auto-generated method stub
                    super.run();
                    try {
    
                        System.out.println("Ping");
                        q.put(1);
                        q.put(2);
                    } catch (Exception e) {
    
                    }
                }
            }
    
        };
    
        private Thread t2 = new Thread() {
    
            @Override
            public void run() {
    
                while (true) {
                    // TODO Auto-generated method stub
                    super.run();
                    try {
                        q.take();
                        System.out.println("Pong");
                        q.take();
    
                    } catch (Exception e) {
    
                    }
    
                }
    
            }
    
        };
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            PingPongPattern p = new PingPongPattern();
            p.t1.start();
            p.t2.start();
        }
    }
    

提交回复
热议问题