zoukankan      html  css  js  c++  java
  • 多个线程顺序打印问题

    信号量实现

    public class PrintABCUsingSemaphore {
        private int times;
        private Semaphore semaphoreA = new Semaphore(1);
        private Semaphore semaphoreB = new Semaphore(0);
        private Semaphore semaphoreC = new Semaphore(0);
    
        public PrintABCUsingSemaphore(int times) {
            this.times = times;
        }
    
        public static void main(String[] args) {
            PrintABCUsingSemaphore printABC = new PrintABCUsingSemaphore(10);
    
            // 非静态方法引用  x::toString   和() -> x.toString() 是等价的!
            new Thread(printABC::printA).start();
            new Thread(printABC::printB).start();
            new Thread(printABC::printC).start();
    
            /*new Thread(() -> printABC.printA()).start();
            new Thread(() -> printABC.printB()).start();
            new Thread(() -> printABC.printC()).start();
    */
        }
    
        public void printA() {
            try {
                print("A", semaphoreA, semaphoreB);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        public void printB() {
            try {
                print("B", semaphoreB, semaphoreC);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        public void printC() {
            try {
                print("C", semaphoreC, semaphoreA);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        private void print(String name, Semaphore current, Semaphore next)
                throws InterruptedException {
            for (int i = 0; i < times; i++) {
                current.acquire();
                System.out.print(name);
                next.release();
            }
        }
    }
  • 相关阅读:
    month(字段)、year(字段)
    简单音乐播放器实现
    Mp3音乐文件列表实现
    读取SD卡中所有MP3文件
    java基础复习 之 多态
    JavaWeb学习过程 之c3p0的使用
    JavaWeb学习过程 之MVC模式下的查询
    行转列:总结
    如何快速禁用约束 (解决ORA-O2266问题)
    PLSQL Developer 11 使用技巧(持续更新)
  • 原文地址:https://www.cnblogs.com/dongma/p/10039888.html
Copyright © 2011-2022 走看看