java实现【有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABC.】

该题应属于生产者消费者模式一类

 

生产者消费者模式:根据标志位来发消息,实现对线程的控制。

 

直接贴答案了,请各位大虾们指正哦。

 

创建三个线程 如下:ThreadA、ThreadB、ThreadC

 

public class ThreadA implements Runnable {

 Printer printer;

 ThreadA(Printer printer) {
  this.printer = printer;
 }

 public void run() {
  for (int i = 0; i < 10; i++) {
   printer.printThreadA();
  }
 }

}

 

控制打印的类:

 

public class Printer {

 int flag = 0;

 public synchronized void printThreadA() {
  if (flag == 0) {
   System.out.print("A");
   flag = 1;
   notifyAll();
  }
  try {
   wait();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public synchronized void printThreadB() {
  if (flag == 1) {
   System.out.print("B");
   flag = 2;
   notifyAll();
  }
  try {
   wait();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public synchronized void printThreadC() {
  if (flag == 2) {
   System.out.print("C");
   flag = 0;
   notifyAll();
  }
  try {
   wait();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 

main方法:

 

 public static void main(String[] args) {

  Printer printer = new Printer();
  ThreadA ta = new ThreadA(printer);
  ThreadB tb = new ThreadB(printer);
  ThreadC tc = new ThreadC(printer);

  Thread t = new Thread(ta);
  t.start();
  Thread tt = new Thread(tb);
  tt.start();
  Thread ttt = new Thread(tc);
  ttt.start();
 }

 

你可能感兴趣的:(java实现【有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABC.】)