二十六位英文字母中兩個線程交替打印字母

面試中碰見兩個線程交替打印字母,要求元音字母爲一個線程,廢話不多說,代碼直接上,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狀態

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章