Multithreading - meter race

Topic: meter race

 

10 athletes meter race, requirements:

1. At the same time start

2. All athletes are considered the end of the game to reach the end

3. Output standings

import java.util.ArrayList;

9/**

10   *

11 * CountDownLatch and ready to race by athletes achieve CyclicBarrier -> starting gun to start running - calculated score> to reach the end

 

15   */

16public class CountDownLatchTest1 {

The amount of the number of 18 athletes

19         private static int SPORTSMAN_COUNT = 10;

20

21   private static final Random random = new Random();

Before Use 23 for issuing the order to determine whether the athletes gets into the ready state, need to wait 10 athletes ready to occupy lock, wait 10 players to complete, release the lock.

24         private static CountDownLatch readyLatch = new CountDownLatch(SPORTSMAN_COUNT);

// Use 25 for determining whether the referee issuing the order, possession of a lock, waiting for the referee issuing the order is completed, the lock is released

26         private static CountDownLatch startLatch = new CountDownLatch(1);

27 // Set the end of the barrier, used to calculate the score Use

28         private static CyclicBarrier cb = new CyclicBarrier(SPORTSMAN_COUNT, new Runnable() { 29

30                  @Override

31                  public void run() {

32

33                          CountDownLatchTest1.transcript

34                          .sort((Sportsman p1, Sportsman p2) -> p1.getTranscript() - p2.getTranscript());

35

System 36. OUT .println ( "ranking report card:" + CountDownLatchTest1. The Transcript );

37

38                          CountDownLatchTest1.transcript.clear();

39                          }

40                          });

41

42 // report card

43         private static List<Sportsman> transcript = new ArrayList<Sportsman>(SPORTSMAN_COUNT);

44

45            public static void main(String[] args) {

47 Using determine whether before issuing the order for the athlete gets into the ready state has to wait 10 athletes ready to occupy lock, wait 10 players to complete, release the lock.

48                  // CountDownLatch readyLatch = new CountDownLatch(SPORTSMAN_COUNT);

// Use 49 for determining whether the referee issuing the order, possession of a lock, waiting for the referee issuing the order is completed, the lock is released

50                  // CountDownLatch startLatch = new CountDownLatch(1);

52 start 10 threads, that is, 10 athletes prepare ⼯ work

53                          for (int i = 0; i < SPORTSMAN_COUNT; i++) {

T = the Thread 54 is new new the Thread ( new new runTask ((I +. 1) + "No. athlete", readyLatch , startLatch ));

55                          t.start();

57 // current athletes in other athletes ready to previous picture has been waiting for, that is to say, etc. readyLatch countdown counter is ⼀ waits before 0

58                          try {

59                          readyLatch.await();

60                          } catch (InterruptedException e) {

61 e.printStackTrace ();

63 // referee issuing the order, the lock is released

64                  startLatch.countDown();

. 65 System OUT .println ( "Referee: all athletes ready to start running ...");

66

67      }

68

69 // athletes

70         static class Sportsman { 71 private String name;

72       private int transcript;

73

74                          public Sportsman(String name, int transcript) {

75                          this.name = name;

76                          this.transcript = transcript;

77                          }

78

79                  @Override

80                  public boolean equals(Object obj) { 81 boolean result = false;

82                                  if (obj instanceof Sportsman) {

83                                  result = ((Sportsman) obj).getTranscript() == this.transcript;

84                                  }

85                                  return result;

86                                  }

87

88                          @Override

89                          public String toString() {

90                          return this.name + ":" + this.transcript + " ms";

91                          }

92

93                          public String getName() {

94                          return name;

95                          }

96

97                          public int getTranscript () {

98                          return transcript;

99                          }

100

101     }

102

103 // run task

104          static class RunTask implements Runnable { 105

106      private Lock lock = new ReentrantLock();

107

108                  private CountDownLatch ready;

109                  private CountDownLatch start;

110                  private String name;

111

112                          /**

113                          *

114 * (configuration ⽅ Method)

115                          *

116                          * @param ready

117                          * @param start

* 118 @param name the name of athletes

119                          */

120                          public RunTask(String name, CountDownLatch ready, CountDownLatch start) {

121                          this.ready = ready;

122                          this.start = start;

123                          this.name = name;

124                          }

125

126                          @Override

127                          public void run() {

128                          lock.lock();

129                          try {

130

131 // 1. Write a logical athletes ready, ready readyTime seconds

132                                           int readyTime = random.nextInt(1000);

. 133 System OUT .println (name + ": I need to" + readyTime + "seconds of time to prepare.");

134                                           try {

135                                           Thread.sleep(readyTime);

136                                           } catch (InterruptedException e) {

137 e.printStackTrace ();

138                                           }

System 139. OUT .println (name + "I'm ready!"); 140 // release the lock readyLatch-1, represents an athlete is ready ⼀

141           ready.countDown();

143 to be the referee made a start command

144                                           start.await();

145                                           } catch (InterruptedException e) {

146

147                                           }

148                                           System.out.println(name + ":开跑...");

149                                           int costTime = random.nextInt(500);

150                                           try {

151                                           Thread.sleep(costTime);

152                                           } catch (InterruptedException e) {

153 e.printStackTrace ();

154                                           }

. 155 System OUT .println (name + ": open ran up to the end result:." + CostTime + "ms ");

156                                           transcript.add(new Sportsman(name, costTime));

157 // Wait for results

158                                           cb.await();

159                                           } catch (Exception e) {

160

161                                  } finally {

162                                  lock.unlock();

163                                  }

164

165         }

166

167     }

168

169}

Guess you like

Origin www.cnblogs.com/cdlyy/p/12061146.html