• Guarded Suspension Pattern【其他模式】


    Guarded Suspension Pattern

    public class GuardedSuspension {
        /**
         * Guarded Suspension Pattern【保护悬挂模式】:如果目标对象不在指定的状态下,则执行警戒方法时,
         *  当前线程将阻塞等待,直到目标对象进入指定状态为止。
         */
        @Test
        public void all() throws InterruptedException {
            final Disk disk = new Disk();
            CompletableFuture.runAsync(() -> new Consumer(disk).consume());
            TimeUnit.SECONDS.sleep(2);
            new Produer(disk).produce();
            TimeUnit.SECONDS.sleep(2);
        }
    }
    
    @AllArgsConstructor
    @Slf4j
    class Consumer {
        private final Disk disk;
    
        public void consume() {
            synchronized (disk) {
                if (disk.empty()) {
                    log.info("current thread is waiting now. {}", Thread.currentThread().getName());
                    try {
                        disk.wait();
                        log.info("take item {}", disk.take());
                    } catch (final InterruptedException e) {
                        log.error("Interrupted", e);
                    }
                }
            }
        }
    }
    
    @AllArgsConstructor
    class Produer {
        private final Disk disk;
    
        public void produce() {
            synchronized (disk) {
                if (disk.empty()) {
                    disk.put(Thread.currentThread().getName());
                    disk.notify();
                }
            }
        }
    }
    
    class Disk {
        private transient String item;
    
        public boolean empty() {
            return StringUtils.isBlank(item);
        }
    
        public String take() {
            final String take = item;
            item = null;
            return take;
        }
    
        public void put(String item) {
            if (StringUtils.isBlank(item)) {
                throw new IllegalStateException("invalid item ");
            }
            this.item = item;
        }
    }
    
    
  • 相关阅读:
    git介绍
    Oracle '26-2月 -19 03.34.47.000000 下午' 字符串日期解析
    ProceedingJoinPoint 某些方法记录一下
    SpringBoot 2.X以上集成redis
    SpringBoot文件上传配置
    editmd输出到前端显示
    Thymeleaf Shiro标签
    Springboot 添加druid监控
    基于SpringBoot的博客项目
    SpringBoot默认首页配置
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10192660.html
Copyright © 2020-2023  润新知