多线程学习二十七:同步模式之顺序控制(顺序输出和交替输出)

固定运行顺序

使用 wait notify

public class Test39 {
    // 用来同步的对象
    static Object obj = new Object();
    // t2 运行标记, 代表 t2 是否执行过
    static boolean t2runed = false;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (obj) {
                // 如果 t2 没有执行过
                while (!t2runed) {
                    try {
                        // t1 先等一会
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.print(1);
        });
        Thread t2 = new Thread(() -> {
            System.out.print(2);
            synchronized (obj) {
                // 修改运行标记
                t2runed = true;
                // 通知 obj 上等待的线程(可能有多个,因此需要用 notifyAll)
                obj.notifyAll();
            }
        });
        t1.start();
        t2.start();
    }
}

Park Unpark顺序输出

public class Test40 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try { 
            Thread.sleep(1000); 
            } catch (InterruptedException e) {}
            // 当没有『许可』时,当前线程暂停运行;有『许可』时,用掉这个『许可』,当前线程恢复运行
            LockSupport.park();
            System.out.println("1");
        });
        Thread t2 = new Thread(() -> {
            System.out.println("2");
            // 给线程 t1 发放『许可』(多次连续调用 unpark 只会发放一个『许可』)
            LockSupport.unpark(t1);
        });
        t1.start();
        t2.start();
    }

}

交替输出

使用wait notify交替输出

**
 * wait notify交替输出
 */
public class Test41 {
    /**
     * 等待标记
     */
    private int falg;

    /**
     * 打印次数
     */
    private int printNumber;

    public Test41(int falg, int printNumber) {
        this.falg = falg;
        this.printNumber = printNumber;
    }

    /**
     * @param string   要打印的字符串
     * @param nowFalg  本次打印的标记
     * @param nextFlag 下次打印的标记
     * @throws InterruptedException
     */
    private void print(String string, int nowFalg, int nextFlag) throws InterruptedException {

        for (int i = 0; i < printNumber; i++) {
            synchronized (this) {
                while (this.falg != nowFalg) {
                    this.wait();
                }
                System.out.print(string+",");
                this.falg = nextFlag;
                this.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        Test41 syncWaitNotify = new Test41(1, 5);
        new Thread(() -> {
            try {
                syncWaitNotify.print("a", 1, 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                syncWaitNotify.print("b", 2, 3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                syncWaitNotify.print("c", 3, 1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}
运行结果
a,b,c,a,b,c,a,b,c,a,b,c,a,b,c,

使用Lock 条件变量交替输出

public class Test42 extends ReentrantLock {
    public static void main(String[] args) throws InterruptedException {
        Test42 as = new Test42(5);
        Condition aWaitSet = as.newCondition();
        Condition bWaitSet = as.newCondition();
        Condition cWaitSet = as.newCondition();
        new Thread(() -> {
            as.print("a", aWaitSet, bWaitSet);
        }).start();
        new Thread(() -> {
            as.print("b", bWaitSet, cWaitSet);
        }).start();
        new Thread(() -> {
            as.print("c", cWaitSet, aWaitSet);
        }).start();
        Thread.sleep(1000);
        as.lock();
        try {
            aWaitSet.signal();
        } finally {
            as.unlock();
        }
    }

    /**
     * 打印次数
     */
    private int loopNumber;

    public Test42(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    /**
     * @param str              打印内容g
     * @param currentCondition 进入哪一间休息室
     * @param nextCondition    下一间休息室
     */
    public void print(String str, Condition currentCondition, Condition nextCondition) {
        for (int i = 0; i < loopNumber; i++) {
            this.lock();
            try {
                currentCondition.await();
                System.out.print(str + ",");
                nextCondition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                this.unlock();
            }
        }
    }
}
运行结果
a,b,c,a,b,c,a,b,c,a,b,c,a,b,c,

使用park unpark 条件变量交替输出

/**
 * 使用park unpark 条件变量交替输出
 */
public class Test43 extends ReentrantLock {
    private static Thread t1;
    private static Thread t2;
    private static Thread t3;

    public static void main(String[] args) throws InterruptedException {
        SyncPark syncPark = new SyncPark(5);
        t1 = new Thread(() -> {
            syncPark.print("a", t2);
        });
        t2 = new Thread(() -> {
            syncPark.print("b", t3);
        });
        t3 = new Thread(() -> {
            syncPark.print("c", t1);
        });
        t1.start();
        t2.start();
        t3.start();
        LockSupport.unpark(t1);

    }
}

class SyncPark {
    private int loopNumber;

    public SyncPark(int loopNumber) {
        this.loopNumber = loopNumber;
    }
    public void print(String str, Thread nextThread) {
        for (int i = 0; i < loopNumber; i++) {
            LockSupport.park();
            System.out.print(str + ",");
            LockSupport.unpark(nextThread);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值