• 非公平锁


    非公平锁:

     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(false);
     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 }

    运行结果如下:

      

  • 相关阅读:
    C语言|博客作业07
    C语言|博客作业06
    C语言|博客作业05
    C语言|博客作业04
    C语言|博客作业03
    C语言I博客作业02
    我的第一周作业!
    第三周作业
    读书笔记《莫让青春沾染暮气》
    第二周作业
  • 原文地址:https://www.cnblogs.com/wang1001/p/9566887.html
Copyright © 2020-2023  润新知