多线程-按顺序打印数字

多线程-按顺序打印数字

打印1到9这9个数字,由A线程先打印1,2,3,然后由B线程打印4,5,6,然后再由A线程打印7,8,9。

思路:明显的条件等待和通知机制,很自然的用 condition即可。

现在我们使用Condition来做这道题:

package com.wangjia;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class App {
    public static void main(String[] args) {
        Printer printer = new App().new Printer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    printer.print4To6();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                printer.print1To3();
                try {
                    printer.print7To9();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    class Printer {
        final Lock lock = new ReentrantLock();
        final Condition reachThreeCondition = lock.newCondition();
        final Condition reachSixCondition = lock.newCondition();

        private int value = 1;

        void print4To6() throws InterruptedException {
            lock.lock();
            try {
                if (value <= 3) {
                    reachThreeCondition.await();
                }
                while (value >= 4 && value <= 6) {
                    System.out.println(value);
                    value++;
                }
                reachSixCondition.signal();
            } finally {
                lock.unlock();
            }
        }

        void print1To3() {
            lock.lock();
            try {
                while (value <= 3) {
                    System.out.println(value);
                    value++;
                }
                reachThreeCondition.signal();
            } finally {
                lock.unlock();
            }
        }

        void print7To9() throws InterruptedException {
            lock.lock();
            try {
                if (value <= 6) {
                    reachSixCondition.await();
                }
                while (value >= 7 && value <= 9) {
                    System.out.println(value);
                    value++;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

输出结果

1
2
3
4
5
6
7
8
9

发表评论

电子邮件地址不会被公开。 必填项已用*标注