zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
    
  • 相关阅读:
    前端必备书籍
    搜索引擎的使用技巧
    PS切图
    css背景透明
    前端
    连接查询,A连B,B筛选出多条记录时,选用第一条记录
    mssql 过滤重复记录,取第一笔记录
    MongoDB 日常操作
    OEE计算
    Aspose.Cells: excel 转 pdf
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10192660.html
Copyright © 2011-2022 走看看