Java多线程的临界资源问题解决方案

2020-02-11 16:00:28王旭

import java.util.concurrent.locks.ReentrantLock;

public class SourceConflict3 {
  public static void main(String[] args) {
    //实例化4个售票员,用4个线程模拟4个售票员
    
    //显式锁
    ReentrantLock lock = new ReentrantLock();
    Runnable r = () -> {
      while (TicketCenter.restCount > 0) {
        lock.lock();
        if (TicketCenter.restCount <= 0) {
          return;
        }
        System.out.println(Thread.currentThread().getName() + "卖出一张票,剩余" + --TicketCenter.restCount + "张票");
        lock.unlock();
      }
    };
    
    //用4个线程模拟4个售票员
    Thread thread1 = new Thread(r, "thread-1");
    Thread thread2 = new Thread(r, "thread-2");
    Thread thread3 = new Thread(r, "thread-3");
    Thread thread4 = new Thread(r, "thread-4");
    
    //开启线程
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
    
  }  
}
class TicketCenter{
  public static int restCount = 100; 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。