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;
        }
    }
    
    
  • 相关阅读:
    python直接赋值、浅拷贝与深拷贝的区别解析
    join shuffle
    Python工作流-Airflow
    【JAVA基础语法】(一)Arrays.asList的使用
    Java中的数组和List
    ArrayList和LinkedList区别
    Array和ArrayList区别
    iOS项目崩溃日志采集与分析
    iOS超全开源框架、项目和学习资料汇总
    iOS webView、WKWebView、AFNetworking 中的cookie存取
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10192660.html
Copyright © 2011-2022 走看看