二十六位英文字母中两个线程交替打印字母

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:50   1943   0

面试中碰见两个线程交替打印字母,要求元音字母为一个线程,废话不多说,代码直接上,talk is cheaper,show me your code。

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PrintChar {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static Condition condition1 = lock.newCondition();
    private static char index = 'a';

    private static List<Character> list;
    static {
        list = Arrays.asList(new Character[]{'a','e','i','o','u'});
    }

    public static void main(String[] args) {
        new Thread(new Condition_1()).start();
        new Thread(new Condition_2()).start();

    }


    static class Condition_1 implements Runnable {

        @Override
        public void run() {

            while (index <= 'z') {
                lock.lock();
                try {
                    // 非元音字母打印
                    while (list.contains(index)) {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                     }
                    System.out.println(Thread.currentThread().getName() + "----" + index);
                    if (index == 'z') {
                        return;
                    }
                    index++;
                    condition1.signal();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    static class Condition_2 implements Runnable {

        @Override
        public void run() {
            if (index > 'z') {
                return;
            }
            while (index <= 'z') {
                lock.lock();
                try {
                    // 元音字母打印
                    while (!list.contains(index)) {
                        try {
                            condition1.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }                                                                                                                                                                               5
                    System.out.println(Thread.currentThread().getName() + "---" + index);
                    index++;
                    condition.signal();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}

但是当前代码是存在问题的,当字母打印完毕之后,两个线程一直处于wait状态

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP