我创建了一个小型电影租赁模拟程序。以下是它的工作原理: - 主线程允许用户输入客户名称
所以这个似乎完全正常工作;它适用于添加的前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;
}
}
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;
}
}
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;
}
}
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;
}
}
答案 0 :(得分:6)
尝试在Semphore构造函数调用中添加true
作为第二个参数。
默认情况下,没有尝试公平,你需要让所有租客轮流。通常,刚刚返回电影的租用者将比等待信号量的人更快地进入acquire
调用。添加true
参数后,“此信号量将保证在争用情况下先进先出授权”Semaphore
答案 1 :(得分:2)
您的代码的问题在于您的客户线程运行无限循环并在发布后立即尝试获取信号量(另一种方法是客户线程应该执行其业务并终止)。第6个线程实际上正在等待转弯但是获得许可的可能性较小,因为前5个线程处于活动状态。要检查这一点,您可以在释放semaphore
许可后将线程置于定时睡眠状态。
此外,闩锁正以错误的方式使用。一旦等待所有5个线程呼叫await
countdown