zoukankan      html  css  js  c++  java
  • 线程安全方式03---Lock锁

    /**
    * 线程安全---Lock方式
    *
    * @Author: ITYW
    * @Create 2020 - 10 - 26 - 19:16
    */
    public class RunnableSecurity_Lock {
    public static void main(String[] args) {
    Runnable_Lock runnable_lock = new Runnable_Lock();
    Thread t1 = new Thread(runnable_lock);
    Thread t2 = new Thread(runnable_lock);
    Thread t3 = new Thread(runnable_lock);

    t1.setName("window01");
    t2.setName("window02");
    t3.setName("window03");

    t1.start();
    t2.start();
    t3.start();
    }
    }
    class Runnable_Lock implements Runnable{
    private static int ticket = 100;
    private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
    while (true){
    try {
    lock.lock();
    if (ticket > 0){
    try {
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"卖出了第"+ticket+"张");
    ticket--;
    }else {
    break;
    }
    } finally {
    lock.unlock();
    }
    }
    }
    }
  • 相关阅读:
    Best Time to Buy and Sell Stock III
    Valid Palindrome
    Longest Substring Without Repeating Characters
    Copy List with Random Pointer
    Add Two Numbers
    Recover Binary Search Tree
    Anagrams
    ZigZag Conversion
    Merge k Sorted Lists
    Distinct Subsequences
  • 原文地址:https://www.cnblogs.com/ITYW/p/13880547.html
Copyright © 2011-2022 走看看