zoukankan      html  css  js  c++  java
  • 公平锁

    公平锁:

     1 import java.util.concurrent.locks.ReentrantLock;
     2 
     3 public class Service {
     4     
     5     private ReentrantLock lock;
     6     
     7     public Service(boolean isFair) {
     8         lock = new ReentrantLock();
     9     }
    10 
    11     public void serviceMethod() {
    12         try {
    13             lock.lock();
    14             System.out.println(Thread.currentThread().getName() + "获取的锁");
    15         } finally {
    16             lock.unlock();
    17         }
    18     }
    19 }
     1 public class Run {
     2 
     3     /**
     4      *    公平锁
     5      */
     6     public static void main(String[] args) {
     7         final Service service = new Service(true);
     8         
     9         Runnable runnable = new Runnable() {
    10             @Override
    11             public void run() {
    12                 System.out.println("线程:" + Thread.currentThread().getName());
    13                 service.serviceMethod();
    14             }
    15         };
    16         
    17         Thread[] threads = new Thread[10];
    18         for (int i = 0; i < 10; i++) {
    19             threads[i] = new Thread(runnable);
    20         }
    21         for (int i = 0; i < 10; i++) {
    22             threads[i].start();
    23         }
    24     }
    25 }

    运行结果如下:

      

  • 相关阅读:
    Max Sum Plus Plus_DP
    Prime Ring Problem_DFS
    Swaps in Permutation _并查集 + 优先队列
    Roadblocks_次短路
    Reward_toposort
    确定比赛名次_toposort
    Zipper_DFS
    Chopsticks_DP
    搬寝室_DP
    Passing the Message_单调栈
  • 原文地址:https://www.cnblogs.com/wang1001/p/9566864.html
Copyright © 2011-2022 走看看