source = new ArrayList<>(base); for (int i = 0; i < base; i++) { source.add(i); }
// 打乱集合顺序 Collections.shuffle(source); }
publicstaticvoidmain(String[] args){ RateBarrier rateBarrier = new RateBarrier(10);
IntStream.range(0, 20).parallel().forEach(i -> { int rate = rateBarrier.rate(); if (rate < 2) { System.out.println("this is on 2"); } elseif (rate < 5) { System.out.println("this is on 3"); } else { System.out.println("this is on 5"); } });
// final Thread[] threads = new Thread[20]; // for (int i = 0; i < threads.length; i++) { // threads[i] = new Thread(() -> { // if (rateBarrier.allow()) { // System.out.println("this is on 3"); // } else { // System.out.println("this is on 7"); // } // }); // threads[i].start(); // } // // for (Thread t : threads) { // try { // t.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }
} }
// Output:
/* this is on 3 this is on 3 this is on 5 this is on 2 this is on 5 this is on 5 this is on 5 this is on 3 this is on 3 this is on 3 this is on 5 this is on 2 this is on 2 this is on 5 this is on 5 this is on 5 this is on 5 this is on 3 this is on 2 this is on 5 */
// 2:3:5 b := NewRateBarrier(10) for i := 0; i < 20; i++ { gofunc() { rate := b.Rate() switch { case rate < 2: fmt.Println("this is on 20%") case rate >= 2 && rate < 5: fmt.Println("this is on 30%") case rate >= 5: fmt.Println("this is on 50%") }
wg.Done() }() }
wg.Wait() }
// Output: /* this is on 30% this is on 50% this is on 30% this is on 20% this is on 50% this is on 50% this is on 50% this is on 20% this is on 30% this is on 20% this is on 50% this is on 30% this is on 30% this is on 50% this is on 50% this is on 50% this is on 20% this is on 50% this is on 50% this is on 30% */