多线程设计模式

1、固定运行顺序

比如,必须先2后1打印

1、wait / notify 版本
package com.sharing_model.synchronous_mode;


/**
 * 同步模式之顺序控制
 * 固定运行顺序: wait notify版
 *
 * 实现效果:必须先2后1执行
 */
public class SequentialControl {
    static final Object lock = new Object();

    //表示t2是否运行过
    static boolean t2runned = false;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                while (!t2runned) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("1");
                }
            }
        },"t1");

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("2");
                t2runned = true;
                lock.notify();
            }
        },"t2");
        
        t1.start();
        t2.start();
    }
}
2、await / signal 版本
package com.sharing_model.synchronous_mode;

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

/**
 * 同步模式之顺序控制
 * 固定运行顺序: await signal版
 *
 * 实现效果:必须先2后1执行
 */
public class SequentialControl2 {
    private static ReentrantLock lock = new ReentrantLock();

    //表示t2是否运行过
    static boolean t2runned = false;

    public static void main(String[] args) {
        Condition condition_1 = lock.newCondition();

        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                while (!t2runned) {
                    condition_1.await();
                    System.out.println("1");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("2");
                t2runned = true;
                condition_1.signal();
            } finally {
                lock.unlock();
            }
        }, "t2");

        t1.start();
        t2.start();
    }
}
3、park / unpark 版本
package com.sharing_model.synchronous_mode;

import java.util.concurrent.locks.LockSupport;

/**
 * 同步模式之顺序控制
 * 固定运行顺序: park unpark 版本
 *
 * 实现效果:必须先2后1执行
 */
public class SequentialControl3 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            LockSupport.park();
            System.out.println("1");
        },"t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            System.out.println("2");
            LockSupport.unpark(t1);
        });
        t2.start();
    }
}

2、交替运行顺序

线程1输出a 5次,线程2输出b5次,线程3输出c5次。现在要求输出abcabcabcabcabc怎么实现

1、wait / notify 版本
package com.sharing_model.synchronous_mode.alternate_order;

/**
 *  同步模式之顺序控制
 *  交替运行顺序: wait notify版
 *
 * 线程1输出a 5次,线程2输出b5次,线程3输出c5次。现在要求输出abcabcabcabcabc怎么实现
 */

/**分析:
 * 输出内容     等待标记    下一个标记
 *   a            1         2
 *   b            2         3
 *   c            3         1
 */
public class AlternateControl1 {
    public static void main(String[] args) {
        WaitNotify wn = new WaitNotify(1, 5);

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

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

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

    }
}


class WaitNotify {
    //等待标记
    private int flag;
    //循环次数
    private int loopNumber;

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

    public void print(String str, int waitFlg, int nextFlag) {
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this) {
                //当等待标记不符合时,线程等待
                while (flag != waitFlg) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //否则输出当前字母,然后唤醒其他线程
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}
2、await / signal 版本
package com.sharing_model.synchronous_mode.alternate_order;

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

/**
 *  同步模式之顺序控制
 *  交替运行顺序: await signal 版本
 *
 * 线程1输出a 5次,线程2输出b5次,线程3输出c5次。现在要求输出abcabcabcabcabc怎么实现
 */

public class AlternateControl2 {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);

        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);
        });

        Thread.sleep(1000);

        awaitSignal.lock();
        try {
            System.out.println("开始...");
            a.signal();
        } finally {
            awaitSignal.unlock();
        }

    }

}

class AwaitSignal extends ReentrantLock {
    private int loopNumber;

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

    public void print(String str, Condition current, Condition next) {
        for (int i = 0 ; i < loopNumber ; i++) {
            lock();
            try {
                current.await();
                System.out.print(str);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}
3、park / unpark 版本
package com.sharing_model.synchronous_mode.alternate_order;

import java.util.concurrent.locks.LockSupport;

/**
 *  同步模式之顺序控制
 *  交替运行顺序: park unpark 版本
 *
 * 线程1输出a 5次,线程2输出b5次,线程3输出c5次。现在要求输出abcabcabcabcabc怎么实现
 */
public class AlternateControl3 {
    static Thread t1;
    static Thread t2;
    static Thread t3;
    public static void main(String[] args) throws InterruptedException {

        ParkUnPark pu = new ParkUnPark(5);

        t1 = new Thread(() -> {
            pu.print("a", t2);
        });

        t2 = new Thread(() -> {
            pu.print("b", t3);
        });

        t3 = new Thread(() -> {
            pu.print("c", t1);
        });

        t1.start();
        t2.start();
        t3.start();

        Thread.sleep(1000);
        LockSupport.unpark(t1);
    }
}


class ParkUnPark {

    private int loopNumber;

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

    public void print(String str, Thread next) {
        for (int i = 0; i < loopNumber; i++) {
            LockSupport.park();
            System.out.print(str);
            LockSupport.unpark(next);
        }
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值