I have trouble understanding output of following code.
My understanding is output would not have any particular sequence but PlayerX started, PlayerX and PlayerX died should be in sequence.And we should have all players should in buffer log and should be printed in end.
But sometime sequence is PlayerX started,PlayerX died and then PlayerX and these cases player name is not in buffer sting. Can someone please point what I am missing?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Game {
public static void main(String[] args) {
Ball gameBall = new Ball();
ExecutorService executor = Executors.newFixedThreadPool(5);
Player[] players = new Player[50];
for (int i = 0; i < players.length; i++) {
Player playerTemp = new Player("Player" + i, gameBall);
executor.submit(playerTemp);
players[i] = playerTemp;
System.out.println(players[i].getName1() + " started");
}
for (int i = 0; i < players.length; i++) {
try {
players[i].join();
System.out.println(players[i].getName1() + " died");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* here all thread should die and following line should display
*all player name
* without any particular order
and should be last line.
*/
executor.shutdown();
System.out.println(gameBall.getLog());
}
}
...
class Player extends Thread {
private final String name;
private final Ball ball;
public Player(String aName, Ball aBall) {
name = aName;
ball = aBall;
}
@Override
public void run() {
ball.kick(name);
}
/**
* @return the name
*/
public String getName1() {
return name;
}
}
...
class Ball {
private volatile StringBuffer log;
public Ball() {
log = new StringBuffer();
}
public synchronized void kick(String aPlayerName) {
log.append(aPlayerName + " ");
System.out.println(aPlayerName);
}
public String getLog() {
return log.toString();
}
}