有三个线程ID分别是A、B、C,用多线编程实现,在屏幕上循环打印10次ABCABC…

xiaoxiao2023-11-21  14

class Worker implements Runnable{ /** 全局的一个信息,用来确定是哪个线程在工作 */ private static int count = 0; /** 线程的标志 */ private int id; /** 线程已工作次数 */ private int pCount; public Worker(int id){ this.id = id; } public void run() { synchronized ("lock") { for (;;) { if(count%3==id){ System.out.print(Thread.currentThread().getName()); count++; pCount++; "lock".notifyAll(); if(pCount==10) break; }else{ try { "lock".wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } public static void main(String[] args) { new Thread(new Worker(0),"A").start(); new Thread(new Worker(1),"B").start(); new Thread(new Worker(2),"C").start(); }
转载请注明原文地址: https://www.6miu.com/read-5011355.html

最新回复(0)