Java多线程 循环打印ABC 10次

来源:互联网 发布:java setcolor 编辑:程序博客网 时间:2024/06/04 22:21

问题描述

Java多线程,循环打印”ABC”10次。

代码

public class printABC {    private static int state = 0;    public static void main(String[] args) {        final printABC t = new printABC();        Thread A = new Thread(new Runnable() {            public synchronized void run() {                // 设定打印10次                for (int i = 0; i < 10; i++) {                    synchronized (t) {                        // 如果不满足A的打印条件,则调用wait,一直阻塞                        while (state % 3 != 0) {                            try {                                t.wait();                            } catch (InterruptedException e) {                                e.printStackTrace();                            }                        }                        // 执行到这里,表明满足条件,打印A,设置state                        // 调用notifyAll方法                        System.out.println("A");                        state++;                        t.notifyAll();                    }                }            }        });        Thread B = new Thread(new Runnable() {            public synchronized void run() {                for (int i = 0; i < 10; i++) {                    synchronized (t) {                        while (state % 3 != 1) {                            try {                                t.wait();                            } catch (InterruptedException e) {                                e.printStackTrace();                            }                        }                        System.out.println("B");                        state++;                        t.notifyAll();                    }                }            }        });        Thread C = new Thread(new Runnable() {            public synchronized void run() {                for (int i = 0; i < 10; i++) {                    synchronized (t) {                        while (state % 3 != 2) {                            try {                                t.wait();                            } catch (InterruptedException e) {                                e.printStackTrace();                            }                        }                        System.out.println("C");                        state++;                        t.notifyAll();                    }                }            }        });        A.start();        B.start();        C.start();    }}
1 0
原创粉丝点击