JUC并发编程九 并发架构--循环打印

使用wait-notify方式实现循环打印

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.TestCycle")
public class TestCycle {

    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1,5);

        new Thread(()->{
            waitNotify.print("a",1,2);
        }).start();

        new Thread(()->{
            waitNotify.print("b",2,3);
        }).start();

        new Thread(()->{
            waitNotify.print("c",3,1);
        }).start();
    }

}

class WaitNotify{

    private int flag; // 初始的状态值,使用整数作为标记
    private int loopNum;

    public WaitNotify(int flag, int loopNum){
        this.flag = flag;
        this.loopNum = loopNum;
    }

    public void print(String str, int flag, int nextFlag){
        for (int i = 0; i < loopNum; i++) {
            synchronized (this){
                while(this.flag != flag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print(str);
                this.flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}

使用await-signal方式打印

import lombok.extern.slf4j.Slf4j;

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

@Slf4j(topic = "c.TestCycle")
public class TestCycle {

    static AwaitSignal awaitSignal = new AwaitSignal(5);
    public static void main(String[] args) {
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();

        new Thread(()->{
            awaitSignal.print("a",a,b);
        }).start();
        new Thread(()->{
            awaitSignal.print("b",b,c);
        }).start();
        new Thread(()->{
            awaitSignal.print("c",c,a);
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        awaitSignal.lock();
        try{
           a.signal();
        }finally {
            awaitSignal.unlock();
        }
    }
}

class AwaitSignal extends ReentrantLock {
    private int loopNum;

    public AwaitSignal(int loopNum){
        this.loopNum = loopNum;
    }

    public void print(String str, Condition current, Condition nextCondition){
        for (int i = 0; i < loopNum; i++) {
            lock();
            try{
                current.await();
                System.out.print(str);
                nextCondition.signal();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                unlock();
            }
        }
    }
}

你可能感兴趣的:(java,架构)