79 lines
2.1 KiB
Java
79 lines
2.1 KiB
Java
package exercises.ex_z4;
|
|
|
|
import exercises.Utils;
|
|
|
|
import java.util.Random;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
import static exercises.ex_z4.AuctionState.BIDDING;
|
|
import static exercises.ex_z4.AuctionState.FINISHED;
|
|
|
|
public class Bidder implements Runnable {
|
|
private static int nextId = 0;
|
|
private final String name;
|
|
private final int id;
|
|
private final List<Item> items = new ArrayList<>();
|
|
private Double lastBid = null;
|
|
private final Auctioneer auctioneer;
|
|
|
|
public Bidder(String name, Auctioneer auctioneer) {
|
|
this.name = name;
|
|
this.id = nextId++;
|
|
this.auctioneer = auctioneer;
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
while (true) {
|
|
AuctionState state = auctioneer.getAuctionState();
|
|
if (state == BIDDING) {
|
|
Random rand = new Random();
|
|
double addon = rand.nextDouble(500);
|
|
Bid maximumBid = auctioneer.getMaximumBid();
|
|
double base = maximumBid == null ? 0 : maximumBid.amount();
|
|
lastBid = base + addon;
|
|
auctioneer.placeBid(new Bid(this, lastBid));
|
|
long minSleep = (long) (base * 10);
|
|
try {
|
|
Utils.randomSleep(minSleep, minSleep + 1000);
|
|
} catch (InterruptedException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
} else if (state == FINISHED) {
|
|
break;
|
|
} else {
|
|
auctioneer.stateLock.lock();
|
|
try {
|
|
auctioneer.stateCond.await();
|
|
} catch (InterruptedException e) {
|
|
throw new RuntimeException(e);
|
|
} finally {
|
|
auctioneer.stateLock.unlock();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public void addItem(Item item){
|
|
items.add(item);
|
|
}
|
|
|
|
public String getName() {
|
|
return name;
|
|
}
|
|
|
|
public int getId() {
|
|
return id;
|
|
}
|
|
|
|
public Double getLastBid() {
|
|
return lastBid;
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return "(" + id + ") " + name;
|
|
}
|
|
}
|