多线程实现加一接着减一,连续五次

2019-10-17  本文已影响0人  长孙俊明
class Resources {
        private ReentrantLock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();
        private int number = 0;
        private void add() {
            // 加1
            lock.lock();
            while(number > 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number++;
            System.out.println("加1");
            condition.signalAll();
            lock.unlock();
        }

        private void reduce() {
            // 减1
            lock.lock();
            while(number <= 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number--;
            System.out.println("减1");
            condition.signalAll();
            lock.unlock();
        }
    }

    public void test() {
        Resources resources = new Resources();
        for(int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    resources.add();
                }
            }).start();
        }
        for(int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    resources.reduce();
                }
            }).start();
        }
    }
上一篇下一篇

猜你喜欢

热点阅读