本文主要是介绍并发编程之两阶段终止模式 保护性暂停 顺序与交替模式 总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
保护性暂停可以解耦添加一个消息队列 升级为生产者消费者模式
/*** 用于线程之间等待并传递信息 join方法基于此实现*/static class GuardedObject {//标识private int id;//结果private Object response;public GuardedObject(){}public GuardedObject(int id){this.id = id; }public int getId(){return id;}//超时时间timeoutpublic Object get(long timeout){synchronized (this){//开始时间long begin = System.currentTimeMillis();//经过时间long passedTime = 0;while(response == null){long waitTime = timeout - passedTime;if(timeout - passedTime < 0){break;}try {//设置等待超时this.wait(waitTime);} catch (InterruptedException e) {e.printStackTrace();}passedTime = System.currentTimeMillis() - begin;}return response;}}public void complete(Object response){synchronized (this){this.response = response;//获取到结果唤醒等待对列中所有的值this.notifyAll();}}}
/*** 两阶段终止*/
@Slf4j(topic = "designDemo")
class DesignDemo {private Thread monitor;public void start(){monitor = new Thread(() -> {while (true){Thread thread = Thread.currentThread();if(thread.isInterrupted()){log.debug("线程退出前执行。。。");break;}try {TimeUnit.SECONDS.sleep(1);log.debug("线程监控中。。。");} catch (InterruptedException e) {e.printStackTrace();//出现异常重新打断 异常会将打断标记重置为假thread.interrupt();}}});monitor.start();}public void stop(){monitor.interrupt();}
}
同步顺序模式
@Slf4j(topic = "c.test04")
public class Test04 {//锁static final Object lock = new Object();//t2运行标记static boolean t2runned = false;//wait notify 实现同步顺序执行public static void waitMethod() {Thread t1 = new Thread(()->{synchronized (lock) {//while 防止虚假唤醒while(!t2runned){try{//等待释放锁 t2就能拿到锁lock.wait();}catch (InterruptedException e){e.printStackTrace();}}log.info("1");}},"t1");Thread t2 = new Thread(()->{synchronized (lock){log.info("2");t2runned = true;lock.notify();}},"t2");t1.start();t2.start();}//park 实现public static void parkMethod() {Thread t1 = new Thread(()->{LockSupport.park();log.info("1");},"t1");Thread t2 = new Thread(()->{log.info("2");LockSupport.unpark(t1);},"t2");t1.start();t2.start();}}
交替输出模式
//打印方法 每个线程实现传入打印数据str 自己的等待标记 下一个调用的线程等待标记
public void print(String str, int waitFlag, int nextFlag){for (int i = 0; i < loopNumber; i++) {synchronized (this){while(flag != waitFlag){try{this.wait();}catch (InterruptedException e){e.printStackTrace();}}}}System.out.println(str);flag = nextFlag;this.notifyAll();}private int flag;private int loopNumber;//构造方法初始化第一个线程标记和循环次数public Test05(int flag, int loopNumber){this.flag = flag;this.loopNumber = loopNumber;}
这篇关于并发编程之两阶段终止模式 保护性暂停 顺序与交替模式 总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!