zoukankan      html  css  js  c++  java
  • 多线程顺序打印ABC

    import java.util.concurrent.locks.ReentrantLock;
    
    public class AsynObject {
    
        private volatile int count;
    
        private ReentrantLock lock = new ReentrantLock();
    
        public AsynObject(int count) {
            this.count = count;
        }
    
        public void printA() {
            print("A", 0);
        }
    
        public void printB() {
            print("B", 1);
        }
    
        public void printC() {
            print("C", 2);
        }
    
        private void print(String name, int a) {
            lock.lock();
            try {
                if (count % 3 == a) {
                    System.out.println(name);
                    count++;
                    Thread.sleep(100);
                }
            } catch (Exception ex) {
    
            } finally {
                lock.unlock();
            }
        }
    }
        public static void main(String[] args) {
            AsynObject asynObject = new AsynObject(3);
            Thread printThreadA = new Thread(() -> {
                while (true){
                    asynObject.printA();
                }
            });
            printThreadA.start();
            Thread printThreadB = new Thread(() -> {
                while (true){
                    asynObject.printB();
                }
            });
            printThreadB.start();
            Thread printThreadC = new Thread(() -> {
                while (true){
                    asynObject.printC();
                }
            });
            printThreadC.start();
        }
  • 相关阅读:
    van Emda Boas
    斐波那契堆
    NTT
    FFT
    KDTree
    扩展kmp
    kmp
    Dancing Links
    树的prufer编码
    有向图最小路径覆盖
  • 原文地址:https://www.cnblogs.com/use-D/p/13418578.html
Copyright © 2011-2022 走看看