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();
        }
    }
  • 相关阅读:
    [CF1198D] Rectangle Painting 1
    [CF696B] Puzzles
    [CF540D] Bad Luck Island
    [P1654] OSU!
    [P6154] 游走
    [CF1265E] Beautiful Mirrors
    [CF920F] SUM and REPLACE
    [CF453B] Little Pony and Harmony Chest
    [CF808D] Array Division
    [CF1155D] Beautiful Array
  • 原文地址:https://www.cnblogs.com/rojas/p/5378805.html
Copyright © 2011-2022 走看看