zoukankan      html  css  js  c++  java
  • ReentrantLock

    ReentrantLock:重入锁的意思。与synchronized作用差不多,区别就是synchronized加锁放锁看不见,而这个重入锁加锁放锁看的见

     1 package thread;
     2 
     3 import java.util.concurrent.locks.Lock;
     4 import java.util.concurrent.locks.ReentrantLock;
     5 
     6 public class 重入锁 {
     7     public static void main(String[] args) {
     8         T t = new T();
     9         Thread thread1 = new Thread(t);
    10         Thread thread2 = new Thread(t);
    11         Thread thread3 = new Thread(t);
    12         thread1.start();
    13         thread2.start();
    14         thread3.start();
    15 
    16 
    17     }
    18 }
    19 
    20 class T implements Runnable {
    21     private int count = 10;
    22     private final ReentrantLock lock = new ReentrantLock();
    23     @Override
    24     public void run() {
    25         while (true) {
    26             try {
    27                 // 加锁
    28                 lock.lock();
    29                 if (count > 0) {
    30 
    31                     try {
    32                         Thread.sleep(1000);
    33                     } catch (InterruptedException e) {
    34                         e.printStackTrace();
    35                     }
    36                     System.out.println(--count);
    37                 }
    38             } finally {
    39                 // 解锁
    40                 lock.unlock();
    41             }
    42 
    43 
    44         }
    45     }
    46 }

    一般把加锁解锁放在try finally语句里面包裹

  • 相关阅读:
    数据库设计
    Android入门
    Java
    深入理解计算机
    Python
    JS
    powerdesigner
    计算机程序员+研一生活总结
    影视剧里程序员使用的双显示屏,在生活中真的需要么?
    性质太恶劣,紧张时期竟有人开发假冒健康码软件,幸已下架!
  • 原文地址:https://www.cnblogs.com/YXBLOGXYY/p/14813616.html
Copyright © 2011-2022 走看看