fork download
  1.  
  2. import java.util.Random;
  3. import java.util.concurrent.atomic.AtomicBoolean;
  4.  
  5. public class Main {
  6. public static void main(String[] args) {
  7. final AtomicBoolean flag = new AtomicBoolean(false);
  8.  
  9. final Thread[] runners = new Thread[5];
  10.  
  11. final Random random = new Random();
  12.  
  13. for (int i = 0 ; i < runners.length; i++){
  14. runners[i] = new Thread("Runner # " + i){
  15. @Override
  16. public void run() {
  17. try {
  18. // wait for random time
  19. Thread.sleep(1000 + random.nextInt(1000));
  20.  
  21. // try to claim the flag
  22. boolean claimed = flag.compareAndSet(false,true);
  23.  
  24. if(claimed){
  25. System.out.println(this.getName() + " has won the race.");
  26.  
  27. // interrupt others
  28. for (Thread t : runners){
  29. if(!t.equals(this)){
  30. t.interrupt();
  31. }
  32. }
  33. }else {
  34. System.out.println(this.getName() + " has very closely lost the race.");
  35. }
  36.  
  37. } catch (InterruptedException e) {
  38. System.out.println(this.getName() + " has lost the race.");
  39. }
  40. }
  41. };
  42. }
  43.  
  44. // get set go
  45. for (int i = 0 ; i < runners.length; i++){
  46. runners[i].start();
  47. }
  48. }
  49. }
Success #stdin #stdout 0.08s 381824KB
stdin
Standard input is empty
stdout
Runner # 1 has won the race.
Runner # 0 has lost the race.
Runner # 2 has lost the race.
Runner # 4 has lost the race.
Runner # 3 has lost the race.