java多线程,多线程顺序控制按ABC的顺序显示

  • 编写一个程序,开启3个线程这3个线程的ID分别为A,B,C

  • 每个线程将自己的ID在屏幕上打印10遍

  • 要求输出结果必须按ABC的顺序显示;如:ABCABC ....依次递推

    import java.util.LinkedList;
    
    public class Test{
        static LinkedList<Integer> list = new LinkedList<Integer>();
    
        private static class MyThread extends Thread {
            private String id;
            private MyThread other;
    
            public MyThread(String id,MyThread thread) {
                this.id = id;
                this.other = thread;
            }
    
            public void run() {
                try {
                    synchronized (this) {
                        this.wait();
                    }
                    for (int i = 0; i < 10; i++) {
                        System.out.println(id);
                        Thread.sleep(1000);
                        synchronized (other) {
                            other.notify();
                        }
                        synchronized (this) {
                            this.wait();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
        }
    
        public static void main(String[] args) {
            for (int i = 0; i < 1000000; i++) {
                list.add(i);
            }
            MyThread mt3 = new MyThread("C", null);
            MyThread mt2 = new MyThread("B", mt3);
            MyThread mt1 = new MyThread("A", mt2);
            mt3.other = mt1;
            mt1.start();
            mt2.start();
            mt3.start();
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
            synchronized (mt1) {
                mt1.notify();
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_40629792/article/details/85229126