gpt4 book ai didi

Java同步任务

转载 作者:行者123 更新时间:2023-11-30 08:01:14 24 4
gpt4 key购买 nike

我有一个任务是编写简单的预订系统,除了一件事我已经完成了,最后一个任务我无法正确理解它,你能告诉我如何解决最后一个问题因为我什至不知道如何形成一个关于它的问题并在谷歌中搜索:

  • Try to redesign your application so that it is still thread-safe, but without using locking mechanisms (i.e. without synchronization or java.util.concurrent.locks)

这是我到目前为止编写的代码:

public class Bus{

private final boolean [] seats = new boolean[50];
private int nextSeat = 0;

public void bookSeat() throws Exception{
if(nextSeat<seats.length){
seats[nextSeat]=true;
nextSeat++;
System.out.print("Seat number " +nextSeat+ " booked");
}else{
System.out.println("The bus is full sorry");
}
}

}

public class Passenger extends Thread{

Bus bus;
String passengerName;

public Passenger(Bus bus, String passengerName){
this.bus=bus;
this.passengerName=passengerName;
}

public void run(){
synchronized(bus){
try {
bus.bookSeat();
Thread.sleep(500);
} catch (Exception ex) {
Logger.getLogger(Passenger.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("by " + passengerName);

}
}

public String getPassengerName() {
return passengerName;
}

public void setPassengerName(String passengerName) {
this.passengerName = passengerName;
}
}

public class Main {
public static void main(String [] args) throws InterruptedException{
Bus someCompany = new Bus();

Passenger p1 = new Passenger(someCompany,"Name1");
Passenger p2 = new Passenger(someCompany, "Name2");

p1.start();
p2.start();

}
}

最佳答案

因此您需要使用 java.util.concurrent.atomic 包中的类,实际上它们允许您使您的类线程安全而无需支付锁的代价,因为它们提出了一个无锁方法。

以下是我将如何修改您的代码以使其在不使用内在显式 锁的情况下实现线程安全:

public class Bus {

private final AtomicIntegerArray seats = new AtomicIntegerArray(50);
private final AtomicInteger nextSeat = new AtomicInteger();

public void bookSeat() throws Exception {
// get the next value, then increment the sequence
int next = nextSeat.getAndIncrement();
// check if we don't exceed the size of the array
if (next < seats.length()){
// Set the value at the index "next" to "1" for booked
seats.set(next, 1);
System.out.println("Seat number " +next+ " booked");
} else {
System.out.println("The bus is full sorry");
}
}
}

注意: 我使用 AtomicIntegerArray 因为 boolean 没有等价物,我们需要一个具有 volatile 值的数组,所以 0false1true .

关于Java同步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37917037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com