首页 > 代码库 > Java多线程开启三个线程输出ABC10次

Java多线程开启三个线程输出ABC10次

最近学多线程,搜了一下,满屏幕的问题都是类似标题那样的,所以就拿这个当开始吧,自己试了一下手,

多次把电脑CPU跑到100%,终于还是写出来了,大体思路为:

声明一个变量,标记三个线程该哪个线程输出,每次输出将该变量+1,判断方式为 变量对3的余数,如果为1-A,2-B, 3-C

 1 public class ABC { 2  3     private static int mark = 0; 4  5     private static Object obj = new Object(); 6      7     public static void main(String[] args) throws Exception { 8         ABC abc = new ABC(); 9         new Thread(abc.new PrintA()).start();10         new Thread(abc.new PrintB()).start();11         new Thread(abc.new PrintC()).start();12     }13     14     class PrintA implements Runnable{15 16         @Override17         public void run() {18             for(int i = 0; i < 10; i++){19                 synchronized (obj){20                     while(mark %3 != 0){21                         try {22                             obj.wait();23                         } catch (InterruptedException e) {24                             e.printStackTrace();25                         }26                     }27                     System.out.print("A");28                     mark ++;29                     obj.notifyAll();30                 }31             }32         }33     }34     class PrintB implements Runnable{35 36         @Override37         public void run() {38             for(int i = 0; i < 10; i++){39                 synchronized (obj){40                     while(mark %3 != 1){41                         try {42                             obj.wait();43                         } catch (InterruptedException e) {44                             e.printStackTrace();45                         }46                     }47                     System.out.print("B");48                     mark ++;49                     obj.notifyAll();50                 }51             }52         }53     }54     class PrintC implements Runnable{55 56         @Override57         public void run() {58             for(int i = 0; i < 10; i++){59                 synchronized (obj){60                     while(mark %3 != 2){61                         try {62                             obj.wait();63                         } catch (InterruptedException e) {64                             e.printStackTrace();65                         }66                     }67                     System.out.println("C");68                     mark ++;69                     obj.notifyAll();70                 }71             }72         }73     }74 }

 

Java多线程开启三个线程输出ABC10次