zoukankan      html  css  js  c++  java
  • java Reentrant Lock

    //Listing 7-1. Achieving Synchronization in Terms of Reentrant Locks
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class A {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(2);
            final ReentrantLock lock = new ReentrantLock();
            class Worker implements Runnable {
                private final String name;
    
                Worker(String name) {
                    this.name = name;
                }
    
                @Override
                public void run() {
                    lock.lock();
                    try {
                        if (lock.isHeldByCurrentThread())
                            System.out.printf(
                                    "Thread %s entered critical section.%n", name);
                        System.out.printf("Thread %s performing work.%n", name);
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException ie) {
                            ie.printStackTrace();
                        }
                        System.out.printf("Thread %s finished working.%n", name);
                    } finally {
                        lock.unlock();
                    }
                }
            }
            executor.execute(new Worker("ThdA"));
            executor.execute(new Worker("ThdB"));
            try {
                executor.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
            executor.shutdownNow();
        }
    }
  • 相关阅读:
    墙奸有感
    关于ubuntu里的fcitx
    Ubuntu 9.10 ati HD 3470 显卡驱动 搞定
    XP与Ubuntu双系统的问题
    invalid conversion from ‘__pthread_t*’ to ‘pid_t’
    Julian Day
    m的n次幂的求法
    Sublime Text 2
    在虚拟机Virtualbox安装Win8消费者版
    记一个循环的错误
  • 原文地址:https://www.cnblogs.com/rojas/p/5378805.html
Copyright © 2011-2022 走看看