多线程顺序打印ABC

Posted use-d

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程顺序打印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();
    }

 

以上是关于多线程顺序打印ABC的主要内容,如果未能解决你的问题,请参考以下文章

三个线程顺序打印ABC?我有十二种做法,彻底掌握多线程同步通信机制

三个线程顺序打印ABC?我有十二种做法,彻底掌握多线程同步通信机制

三个线程顺序打印ABC?我有十二种做法,彻底掌握多线程同步通信机制

三个线程顺序打印ABC?我有十二种做法,彻底掌握多线程同步通信机制

[******] java多线程连续打印abc

java多线程编程之连续打印abc的几种解法