兩個執行緒列印AB
阿新 • • 發佈:2021-08-05
1.使用執行緒實現:兩個執行緒迴圈列印AB
- 思路:主要使用wait、notifyall和synchronized實現
- 程式碼:
public class PrintAB { /** * 上一次列印為A則為true,否則為false */ private static volatile boolean flag = false; public static void main(String[] args) { PrintAB printAB = new PrintAB(); // 1.迴圈列印AB new Thread(() -> printAB.printA()).start(); new Thread(() -> printAB.printB()).start(); } private synchronized void printA() { while(true) { // true表示上一次列印為A if(flag) { try { // 當前執行緒等待 wait(); } catch (Exception e) { e.printStackTrace(); } } System.out.print("A"); // 列印A之後需置換標識為true,表示上一次列印為A flag = true; notifyAll(); } } private synchronized void printB() { while(true) { // 上一次列印不為A,即為B if(!flag) { try { // 當前執行緒等待 wait(); } catch (Exception e) { e.printStackTrace(); } } System.out.print("B"); // 列印B之後需置換標識為false,表示上一次列印為B flag = false; notifyAll(); } } }
2.使用執行緒實現:兩個執行緒迴圈列印AB 10次
- 思路:主要使用wait、notifyall和synchronized實現
- 程式碼:
public class PrintAB { /** * 上一次列印為A則為true,否則為false */ private static volatile boolean flag = false; public static void main(String[] args) { PrintAB printAB = new PrintAB(); // 2.迴圈列印AB 10次 new Thread(() -> printAB.printA2(10)).start(); new Thread(() -> printAB.printB2(10)).start(); } private synchronized void printA2(int N) { int count = 0; while(count < N) { // true表示上一次列印為A if(flag) { try { // 當前執行緒等待 wait(); } catch (Exception e) { e.printStackTrace(); } } System.out.print("A"); count += 1; // 列印A之後需置換標識為true,表示上一次列印為A flag = true; notifyAll(); } } private synchronized void printB2(int N) { int count = 0; while(count < N) { // 上一次列印不為A,即為B if(!flag) { try { // 當前執行緒等待 wait(); } catch (Exception e) { e.printStackTrace(); } } System.out.print("B"); count += 1; // 列印B之後需置換標識為false,表示上一次列印為B flag = false; notifyAll(); } } }