多线程顺序打印ABC


	多线程顺序打印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();
        }
    }
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 多线程顺序打印ABC