栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java题目:多线程的应用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java题目:多线程的应用

题目:按顺序打印 ABC ABC ABC ...。有这么一个多线程场景问题:有三个线程,线程1执行(输出A)完成之后线程2执行(输出B),线程2执行完之后线程3执行(输出C),线程3执行完成之后线程1执行...,整体循环50次,写程序实现。

代码:

class PrintABC {
    private volatile int value = 1;
    void printA() {
        synchronized (this) {
            while (value != 1) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Thread1: A");
            value = 2;
            //唤醒
            notifyAll();
        }
    }
    void printB() {
        synchronized (this) {
            while (value != 2) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Thread2: B");
            value = 3;
            notifyAll();
        }
    }
    void printC() {
        synchronized (this) {
            while (value != 3) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Thread3: C");
            value = 1;
            notifyAll();
        }
    }
}

public class 多线程的应用{

    public static void main(String[] args) throws Exception {
        PrintABC printABC = new PrintABC();

        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 50; i++) {
                    printABC.printA();
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 50; i++) {
                    printABC.printB();
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 50; i++) {
                    printABC.printC();
                }
            }
        }).start();

    }
}

 测试结果:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/972254.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号