三个线程交互打印

2022-03-02  本文已影响0人  xiaohei_e853
package test;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SequencePrintNumber {




    public static void main(String[] args) {

        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition1 = reentrantLock.newCondition();
        Condition condition2 = reentrantLock.newCondition();
        Condition condition3 = reentrantLock.newCondition();

        AtomicInteger atomicInteger = new AtomicInteger();

        new Thread("A"){
            @Override
            public void run() {
                super.run();

                for (int i = 0; i < 10; i++) {

                    try{
                        reentrantLock.lock();

                        int count = atomicInteger.get();

                        if(count%3!=0){

                            condition1.await();
                        }
                        System.out.println(Thread.currentThread().getName()+"111");
                        atomicInteger.getAndAdd(1);

                        condition2.signal();

                    }catch (Exception e){

                    }finally {
                        reentrantLock.unlock();
                    }

                }


            }
        }.start();

        new Thread("B"){
            @Override
            public void run() {
                super.run();

                for (int i = 0; i < 10; i++) {

                    try{
                        reentrantLock.lock();

                        int count = atomicInteger.get();

                        if(count%3!=1){
                            condition2.await();

                        }
                        System.out.println(Thread.currentThread().getName()+"222");
                        atomicInteger.getAndAdd(1);

                        condition3.signal();

                    }catch (Exception e){

                    }finally {
                        reentrantLock.unlock();
                    }

                }


            }
        }.start();

        new Thread("C"){
            @Override
            public void run() {
                super.run();

                for (int i = 0; i < 10; i++) {

                    try{
                        reentrantLock.lock();

                        int count = atomicInteger.get();

                        if(count%3!=2){
                            condition3.await();

                        }
                        System.out.println(Thread.currentThread().getName()+"333");
                        atomicInteger.getAndAdd(1);

                        condition1.signal();

                    }catch (Exception e){

                    }finally {
                        reentrantLock.unlock();
                    }

                }


            }
        }.start();
    }
}

上一篇 下一篇

猜你喜欢

热点阅读