码迷,mamicode.com
首页 > 编程语言 > 详细

多线程顺序打印ABC

时间:2020-08-02 16:13:31      阅读:27      评论:0      收藏:0      [点我收藏+]

标签:while   ntc   int   import   read   imp   vat   catch   unlock   

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();
    }

 

多线程顺序打印ABC

标签:while   ntc   int   import   read   imp   vat   catch   unlock   

原文地址:https://www.cnblogs.com/use-D/p/13418578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!