前提要求:两个线程,一个线程打印 1~52,另一个线程打印字母A-Z。打印顺序为12A34B56C……
直接上代码
public class ThreadTest {public static void main(String[] args) {PrintTask printTask = new PrintTask();Thread numberThread = new Thread(() -> {printTask.printNumber();});Thread letterThread = new Thread(() -> {printTask.printLetter();});numberThread.start();letterThread.start();}
}class PrintTask {private int count = 1;private int num = 1;private char letter = 'A';public synchronized void printNumber() {try {while (count <= 52) {if (count % 2 != 0) {System.out.print(num++);System.out.print(num++);count++;notify(); // 唤醒等待的线程} else {wait(); // 等待}}} catch (InterruptedException e) {e.printStackTrace();}}public synchronized void printLetter() {try {while (count <= 52) {if (count % 2 == 0) {System.out.print(letter++);count++;notify(); // 唤醒等待的线程} else {wait(); // 等待}}} catch (InterruptedException e) {e.printStackTrace();}}
}
执行一下