面试中碰见两个线程交替打印字母,要求元音字母为一个线程,废话不多说,代码直接上,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状态
|