java多线程学习之-两线程分别顺序打印元音字母辅音字母,采用wait-notify
class LetterService {
List<Character> filter = Arrays.asList('a', 'e', 'i', 'o', 'u');
private int letterVal = 1;
public void outVowel() {
while (letterVal <= 26) {
synchronized (this) {
try {
if (filter.contains((char) (letterVal + 96))) {
System.out.println(Thread.currentThread().getName() + "---" + (char) (letterVal + 96));
letterVal++;
notify();
} else {
wait();
}
} catch (Exception e) {
}
}
}
}
public void outconsonant() {
while (letterVal <= 26) {
synchronized (this) {
try {
if (!filter.contains((char) (letterVal + 96))) {
System.out.println(Thread.currentThread().getName() + "---" + (char) (letterVal + 96));
letterVal++;
notify();
} else {
wait();
}
} catch (Exception e) {
}
}
}
}
}
public static void main(String[] args) {
LetterService letterService = new LetterService();
new Thread(() -> letterService.outVowel(), "Thread-元音").start();
new Thread(()->letterService.outconsonant(), "Thread-辅音").start();
}