多线程输出123以及有序输出1-75

一、多线程实现输出循环123

  1、循环输出123,通过Lock锁和共享变量state实现3个线程循环执行

private static volatile int state;
    final static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        for (int i = 0; i < 3; i ++) {

        }
        Worker a = new Worker(3, 0);
        Worker b = new Worker(3, 1);
        Worker c = new Worker(3, 2);
        a.start();
        b.start();
        c.start();
    }

    private static class Worker extends Thread {

        int mod;
        int v;

        Worker(int mod, int v) {
            this.mod = mod;
            this.v = v;
        }

        @Override
        public void run() {
            while (true) {
                lock.lock();
                if (state % mod == v) {
                    System.out.print(v + 1);
                    state++;
                }
                lock.unlock();
            }
        }
    }

二、按照顺序输出1-75

    2、通过condition条件的通知机制和原子变量Inc自增实现输出1-75

    

private static final AtomicInteger inc = new AtomicInteger();

    private static Lock lock = new ReentrantLock();



    public static void main(String[] args) {

        Condition conditionA = lock.newCondition();

        Condition conditionB = lock.newCondition();

        Condition conditionC = lock.newCondition();

        Worker workerA = new Worker(conditionA, conditionB, "A");
        Worker workerB = new Worker(conditionB, conditionC, "B");
        Worker workerC = new Worker(conditionC, conditionA, "C");

        workerA.start();
        workerB.start();
        workerC.start();

    }



    private static class Worker extends Thread {
        private Condition condition;

        private Condition nextCondition;

        private String name;

        Worker(Condition condition, Condition nextCondition, String name) {
            this.condition = condition;
            this.nextCondition = nextCondition;
            this.name = name;
        }

        @Override
        public void run() {
            lock.lock();
            for (int i = 0; i < 5; i++) {
                for (int j = 0; j < 5; j ++) {
                    System.out.println("name: " + name + " v: " + inc.incrementAndGet());
                }
                nextCondition.signalAll();

                if (i < 5) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            lock.unlock();
        }
    }

 

posted @ 2019-06-16 22:14  junxing  阅读(573)  评论(0编辑  收藏  举报