一些线程卡在semaphore.aquire()(threads/semaphore/countdownlatch)

asm*_*smb 2 java multithreading semaphore countdownlatch

我创建了一个小型电影租赁模拟程序.以下是它的工作原理: - 主线程允许用户输入客户名称

  • 每个输入的客户都会启动一个新线程(Customer Runnable)
  • 当创建了5个客户时,租赁服务开始(等待5个倒计时)
  • 当客户运行()时,他们将首先尝试从信号量(具有5个可用许可证)获取()许可证
  • 如果他们获得许可,他们将等待1-10秒,然后租一辆车,然后等待1-3秒,然后开车
  • 当汽车被解除时,他们将全程开始循环迭代并尝试获得新的许可

所以这似乎工作得很好; 它适用于添加的前5个客户.在5号之后添加的客户似乎卡在semaphore.aquire()等待,我无法理解为什么,所以我在这里问.所有的帮助将非常赞赏:)

App.java:

import java.lang.System;import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class App {

    public static CountDownLatch latch = new CountDownLatch(5);
    public static Executor executor = Executors.newCachedThreadPool();
    public static Store store = new Store();
    public static Semaphore semaphore = new Semaphore(Store.getMovies().size());

    Scanner in;

    public App() {
        in = new Scanner(System.in);

        while (true) {
            executor.execute(new Customer(in.nextLine()));
        }
    }

    public static void main(String[] args) {
        new App();
    }

    public CountDownLatch getLatch() {
        return latch;
    }

    public Executor getExecutor() {
        return executor;
    }

    public Semaphore getSemaphore() {
        return semaphore;
    }

}
Run Code Online (Sandbox Code Playgroud)

Customer.java:

public class Customer implements Runnable {

    String name;

    public Customer(String name) {
        this.name = name;
    }

    public void run() {
        try {
            App.latch.countDown();
            App.latch.await();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        // Loop until ended
        while (true) {
            try {
                if (App.semaphore.availablePermits() == 0)
                    System.out.println("No available movies");

                // Acquire permit
                App.semaphore.acquire();

                // Sleep from 1-10 seconds before renting a Car
                int rand = 1 + (int) (java.lang.Math.random() * 10);
                Thread.sleep(rand * 1000);
                App.store.rent(this);

                // Sleep from 1-3 seconds before delivering the Car
                rand = 1 + (int) (Math.random() * 3);
                Thread.sleep(rand * 1000);
                App.store.deliver(this);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                App.semaphore.release();
            }
        }
    }

    public String getName() {
        return name;
    }
}
Run Code Online (Sandbox Code Playgroud)

Store.java:

import java.lang.String;import java.lang.System;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class Store {

    private static List<Movie> movies;

    private static Lock lock = new ReentrantLock();

    public Store() {
        movies = new ArrayList<Movie>();
        movies.add(new Movie("Godfather"));
        movies.add(new Movie("LOTR"));
        movies.add(new Movie("Schindlers list"));
        movies.add(new Movie("Pulp fiction"));
        movies.add(new Movie("Fight club"));
    }

    public void rent(Customer c) {
        lock.lock();
        for (Movie movie : movies) {
            if (movie.getRentedBy() == null) {
                movie.setRentedBy(c);
                String str = c.getName() + " rented " + movie.getName();
                System.out.printf("%-30s", str);
                printStatus();
                break;
            }
        }
        lock.unlock();
    }

    // Deliver the Car
    public void deliver(Customer c) {
        lock.lock();
        for (Movie movie : movies) {
            if (movie.getRentedBy() != null && movie.getRentedBy().equals(c)) {
                movie.setRentedBy(null);
                String str = c.getName() + " delivered " + movie.getName();
                System.out.printf("%-30s", str);
                printStatus();
                break;
            }
        }
        lock.unlock();
    }

    public void printStatus() {
        String str;
        for (Movie m : movies) {
            System.out.print(m.getName() + " - ");
            if (m.getRentedBy() == null) {
                str = "available";
            } else {
                str = "rented by " + m.getRentedBy().getName();
            }
            System.out.printf("%-15s", str);
        }
        System.out.println();
    }

    public static List<Movie> getMovies() {
        return movies;
    }
}
Run Code Online (Sandbox Code Playgroud)

Movie.java:

public class Movie {

    private String name;
    private Customer rentedBy;

    public Movie(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Customer getRentedBy() {
        return rentedBy;
    }

    public void setRentedBy(Customer customer) {
        this.rentedBy = customer;
    }

}
Run Code Online (Sandbox Code Playgroud)

Pat*_*han 6

尝试true在Semphore构造函数调用中添加第二个参数.

默认情况下,没有尝试公平,您需要让所有租房者轮流.通常,刚刚返回电影的租用者acquire将比等待信号量的电影更快地到达呼叫.随着增加的true论点"这个信号量将保证在争用下先获得许可证" Semaphore