java多线程编程之连续打印abc

1. 使用  ReentrantLock

 

package com.concurrent.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SyncPrinter implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock reentrantLock = new ReentrantLock();

        Condition conditionA = reentrantLock.newCondition();
        Condition conditionB = reentrantLock.newCondition();
        Condition conditionC = reentrantLock.newCondition();

        SyncPrinter printerA = new SyncPrinter(reentrantLock, conditionA, conditionB, "A");
        SyncPrinter printerB = new SyncPrinter(reentrantLock, conditionB, conditionC, "B");
        SyncPrinter printerC = new SyncPrinter(reentrantLock, conditionC, conditionA, "C");

        new Thread(printerA).start();
        new Thread(printerB).start();
        Thread.sleep(100);
        new Thread(printerC).start();

    }

    private ReentrantLock reentrantLock;
    private Condition thisCondition;
    private Condition nextCondition;
    private String printStr;

    public SyncPrinter(ReentrantLock reentrantLock, Condition thisCondition, Condition nextCondition, String printStr) {
        this.reentrantLock = reentrantLock;
        this.thisCondition = thisCondition;
        this.nextCondition = nextCondition;
        this.printStr = printStr;
    }

    public void run() {
        try {
            reentrantLock.lock();
            for (int i = 0; i < 10; i++) {
                System.out.println(printStr);
                nextCondition.signal();
                if (i < 9) {
                    thisCondition.await();
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }
}

 

posted @ 2020-03-28 13:23  newlangwen  阅读(192)  评论(0编辑  收藏  举报