三个线程按顺序打印abc

package com.company;


import java.util.LinkedList;
import java.util.Queue;

public class Main {


public static void main(String[] args) throws InterruptedException {
Queue wordList = new LinkedList();
Object todoA = new Object();
Object todoB = new Object();
Object todoC = new Object();
for (int i = 0; i < 100; i++) {
wordList.add('a');
wordList.add('b');
wordList.add("c ");
}
new Thread(new PrintWord("1", wordList, todoA, todoB)).start();
new Thread(new PrintWord("2", wordList, todoB, todoC)).start();
new Thread(new PrintWord("3", wordList, todoC, todoA)).start();
synchronized (todoA) {
todoA.notify();
}

// write your code here
}

public static class PrintWord implements Runnable {
String id;
Queue wordList;
Object todo;
Object todoNext;

private PrintWord(String id, Queue wordList, Object todo, Object todoNext) {
this.id = id;
this.wordList = wordList;
this.todo = todo;
this.todoNext = todoNext;

}

@Override
public void run() {
while (true) {
try {
synchronized (todo) {
todo.wait();
Object _word = wordList.peek();
if (_word != null) {
System.out.print(this.id);
System.out.print(_word);
wordList.remove();
}
synchronized (todoNext) {
todoNext.notifyAll();
}
if (_word == null) break;
}
} catch (InterruptedException e) {
synchronized (todoNext) {
todoNext.notifyAll();
}
e.printStackTrace();
}
}

}
}
}
posted @ 2020-05-15 10:08  java林森  阅读(383)  评论(0编辑  收藏  举报