三个线程轮流执行顺序打印ABC

您所在的位置:网站首页 3个线程交替打印abc 三个线程轮流执行顺序打印ABC

三个线程轮流执行顺序打印ABC

2023-09-13 17:21| 来源: 网络整理| 查看: 265

使用线程同步和通信技术可以实现三个线程轮流打印 ABC。

在 Java 中,可以使用 wait() 和 notify() 方法来实现线程间的同步和通信。

代码示例:

class ABCPrinter { private int state; public void printA() throws InterruptedException { synchronized (this) { while (state % 3 != 0) { wait(); } System.out.print("A"); state++; notifyAll(); } } public void printB() throws InterruptedException { synchronized (this) { while (state % 3 != 1) { wait(); } System.out.print("B"); state++; notifyAll(); } } public void printC() throws InterruptedException { synchronized (this) { while (state % 3 != 2) { wait(); } System.out.print("C"); state++; notifyAll(); } } } class PrinterThread extends Thread { private ABCPrinter printer; private char c; public PrinterThread(ABCPrinter printer, char c) { this.printer = printer; this.c = c; } @Override public void run() { try { if (c == 'A') { printer.printA(); } else if (c == 'B') { printer.printB(); } else if (c == 'C') { printer.printC(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Main { public static void main(String[] args) { ABCPrinter printer = new ABCPrinter(); PrinterThread threadA = new PrinterThread(printer, 'A'); PrinterThread threadB = new PrinterThread(printer, 'B'); PrinterThread threadC = new PrinterThread(printer, 'C'); threadA.start(); threadB.start(); threadC.start(); } }

这个示例代码实现了三个线程轮流打印 ABC 的功能。通过对 state 变量进行控制,并在每个线程内部使用同步块和 wait() 和 notify() 方法实现线程间的同步和通信。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3