我想模拟线程之间的竞争,但有些线程无法启动。如何以这样的方式实现run方法:每个竞争者线程增加一个Counter,当计数器达到值100时,获胜者线程在RaceContext中宣布。每个都有10个团队,每个团队有4个ThreadCompetitors ......这就是我到目前为止所做的:
种族:
public class RelayRace {
private List<RelayRaceTeam> teamList = new ArrayList<>(10);
public RelayRace() {
teamList.add(new RelayRaceTeam("FERRARI"));
teamList.add(new RelayRaceTeam("BMW"));
teamList.add(new RelayRaceTeam("LAMBORGHINI"));
teamList.add(new RelayRaceTeam("DACIA"));
teamList.add(new RelayRaceTeam("NASCAR"));
teamList.add(new RelayRaceTeam("OPEL"));
teamList.add(new RelayRaceTeam("MITSUBISHI"));
teamList.add(new RelayRaceTeam("HONDA"));
teamList.add(new RelayRaceTeam("PORSCHE"));
teamList.add(new RelayRaceTeam("MERCEDES"));
}
public void start() {
teamList.forEach(RelayRaceTeam::start);
}
}
TeamClass:
public class RelayRaceTeam extends Thread {
private static final ThreadRaceContext context = new ThreadRaceContext();
private ArrayList<RelayRaceCompetitor> competitors = new ArrayList<>(4);
private String name;
public RelayRaceTeam(String name) {
this.name = name;
for (int i = 0; i < 4; i++) {
competitors.add(new RelayRaceCompetitor());
}
}
@Override
public void run() {
competitors.forEach(RelayRaceCompetitor::start);
for (RelayRaceCompetitor competitor : competitors) {
System.out.println("Competitor " + competitor.getNumber() + " from team " +
name + " has traversed " + Count.getCounter());
}
if (Count.getCounter() == 100) {
synchronized (context) {
context.announceWhichTeamWon(name, competitors);
}
}
}
}
竞争对手:
public class RelayRaceCompetitor extends Thread{
private int number;
private static final AtomicInteger count = new AtomicInteger(0);
public RelayRaceCompetitor() {
number = count.getAndIncrement();
}
@Override
public void run() {
Count.increment();
}
public int getNumber() {
return number;
}
}
宣布获胜者的背景:
public class ThreadRaceContext extends Thread {
public void announceWhichTeamWon(String name, ArrayList<RelayRaceCompetitor> competitors) {
System.out.println(name + " won the competition");
for (RelayRaceCompetitor competitor : competitors) {
System.out.println("Competitor number : " + competitor.getNumber());
}
}
}
柜台:
public class Count {
private static int counter = 1;
public static void increment() {
counter++;
}
public static int getCounter() {
return counter;
}
}