多线程交替执行

     static  int num=1;
    static  void  test3() throws  InterruptedException{
            Lock lock=new ReentrantLock(true);
            Condition conditionLock1=lock.newCondition();
            Condition conditionLock2=lock.newCondition();
            Condition conditionLock3=lock.newCondition();
            Thread thread1=new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            lock.lock();
                            System.out.println("1");
                           //Thread.sleep(1000);
                            if (num!=1) {
                                conditionLock1.await();
                            }
                            num=2;
                            conditionLock2.signal();
                            lock.unlock();
                        }

                    }catch (Exception e){

                    }

                }
            });
            Thread thread2=new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            lock.lock();
                            System.out.println("2");
                           //Thread.sleep(2000);
                            if (num!=2) {
                                conditionLock2.await();
                            }
                            num=3;
                           conditionLock3.signal();
                           lock.unlock();
                        }
                    }catch (Exception e){

                    }

                }
            });


            Thread thread3=new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            lock.lock();
                            System.out.println("3");
                                //Thread.sleep(3000);
                            if (num!=3) {
                                conditionLock3.await();
                            }
                            num=1;
                            conditionLock1.signal();
                           lock.unlock();
                        }
                    }catch (Exception e){

                    }
                }
            });
            thread2.start();
            thread1.start();
            thread3.start();
        }

执行结果为: 1,2,3,1,2,3````

 

posted @ 2022-03-21 17:36  甜菜波波  阅读(76)  评论(0编辑  收藏  举报