本文整理汇总了Java中java.util.concurrent.ThreadLocalRandom.nextInt方法的典型用法代码示例。如果您正苦于以下问题:Java ThreadLocalRandom.nextInt方法的具体用法?Java ThreadLocalRandom.nextInt怎么用?Java ThreadLocalRandom.nextInt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.ThreadLocalRandom
的用法示例。
在下文中一共展示了ThreadLocalRandom.nextInt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handleDiceRoll
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
private void handleDiceRoll(@NotNull MessageReceivedEvent event, @NotNull List<String> args) {
int upper = Integer.parseUnsignedInt(args.get(0).substring(2));
int iterations = 1;
if (args.size() > 1 && INT_PATTERN.matcher(args.get(1)).find()) {
iterations = Math.min(12, Integer.parseUnsignedInt(args.get(1)));
}
int sIterations = iterations;
ThreadLocalRandom random = ThreadLocalRandom.current();
EmbedBuilder builder = MessageUtils.getEmbedBuilder(event.getMessage().getAuthor());
int sum = 0;
while (iterations-- != 0) {
int num = random.nextInt(1, upper + 1);
sum += num;
builder.appendField(":game_die: [1," + upper + "]", num + "", true);
}
builder.withTitle("Tossed " + sIterations + (sIterations == 1 ? " dice" : " dices"));
builder.withDescription("Average result: " + (sum / sIterations));
sendThenDelete(MessageUtils.getMessageBuilder(event.getMessage())
.withEmbed(builder.build()));
delete(event.getMessage());
}
示例2: chooseIntentions
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
private LinkedList<Action> chooseIntentions(
MentalState.Desire goal, Set<Action> actionsPossible
) {
LinkedList<Action> intentions = new LinkedList<>();
// Ramasse les bijoux avant d'aspirer
if (actionsPossible.contains(Action.GATHER_JEWELRY))
intentions.push(Action.GATHER_JEWELRY);
else if (actionsPossible.contains(Action.VACUUM_DUST))
intentions.push(Action.VACUUM_DUST);
else {
// A random move
ThreadLocalRandom random = ThreadLocalRandom.current();
int countPossibleActions = actionsPossible.size();
int actionNumber = random.nextInt(countPossibleActions);
intentions.push((Action) (actionsPossible.toArray())[actionNumber]);
}
return intentions;
}
示例3: destructiveMedianSimple
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
public static double destructiveMedianSimple(double[] array, int from, int until) {
ThreadLocalRandom random = ThreadLocalRandom.current();
int count = 0;
int index = (from + until) >>> 1;
while (from + 1 < until) {
double pivot = array[++count > 30 ? random.nextInt(from, until) : (from + until) >>> 1];
int l = from, r = until - 1;
while (l <= r) {
while (array[l] < pivot) ++l;
while (array[r] > pivot) --r;
if (l <= r) {
swap(array, l++, r--);
}
}
if (index <= r) {
until = r + 1;
} else if (l <= index) {
from = l;
} else {
break;
}
}
return array[index];
}
示例4: populatedQueue
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
/**
* Returns a new queue of given size containing consecutive
* Integers 0 ... n - 1, with given capacity range and fairness.
*/
static ArrayBlockingQueue<Integer> populatedQueue(
int size, int minCapacity, int maxCapacity, boolean fair) {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int capacity = rnd.nextInt(minCapacity, maxCapacity + 1);
ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(capacity);
assertTrue(q.isEmpty());
// shuffle circular array elements so they wrap
{
int n = rnd.nextInt(capacity);
for (int i = 0; i < n; i++) q.add(42);
for (int i = 0; i < n; i++) q.remove();
}
for (int i = 0; i < size; i++)
assertTrue(q.offer((Integer) i));
assertEquals(size == 0, q.isEmpty());
assertEquals(capacity - size, q.remainingCapacity());
assertEquals(size, q.size());
if (size > 0)
assertEquals((Integer) 0, q.peek());
return q;
}
示例5: testToArray
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
/**
* toArray() and toArray(a) contain all elements in FIFO order
*/
public void testToArray() {
final ThreadLocalRandom rnd = ThreadLocalRandom.current();
final int size = rnd.nextInt(6);
final int capacity = Math.max(1, size + rnd.nextInt(size + 1));
ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(capacity);
for (int i = 0; i < size; i++) {
checkToArray(q);
q.add(i);
}
// Provoke wraparound
int added = size * 2;
for (int i = 0; i < added; i++) {
checkToArray(q);
assertEquals((Integer) i, q.poll());
q.add(size + i);
}
for (int i = 0; i < size; i++) {
checkToArray(q);
assertEquals((Integer) (added + i), q.poll());
}
}
示例6: dealAction
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
public static void dealAction(Player p, Voucher v) {
int rewardCount = 0;
Integer maxRewards = v.getMaxReward();
ThreadLocalRandom rand = ThreadLocalRandom.current();
while (rewardCount <= maxRewards) {
for (String rw : v.getRewards().getKeys(false)) {
List<String> rewards = v.getRewards().getStringList(rw + ".reward");
int chance = v.getRewards().getInt(rw + ".chance");
if (rand.nextInt(100) + 1 <= chance) {
if (rewardCount >= maxRewards) return;
rewardCount++;
for (String reward : rewards) {
RVRewardEvent rewardEvent = new RVRewardEvent(p, v, reward);
Bukkit.getPluginManager().callEvent(rewardEvent);
}
}
}
}
}
示例7: newBuilderInstance
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
private static Builder newBuilderInstance() {
ThreadLocalRandom random = ThreadLocalRandom.current();
return new Builder(UUID.randomUUID().toString(),
random.nextInt(),
UUID.randomUUID().toString(),
Instant.ofEpochMilli(random.nextLong(0, Instant.now().toEpochMilli())));
}
示例8: randomString
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
/**
* Génère une chaine de caractère aléatoire d'une longeur comprise dans un intervalle.
* @param start Taille minimale de la chaine.
* @param end Taille maximale de la chaine.
* @return La chaine de caractère aléatoire
*/
protected String randomString(Integer start, Integer end) {
String characters = "abcdefghijklmnopqrstuvwxyz";
ThreadLocalRandom random = ThreadLocalRandom.current();
Integer length = random.nextInt(start, end);
char[] text = new char[length];
for (int i = 0; i < length; i++) {
text[i] = characters.charAt(random.nextInt(characters.length()));
}
return text.toString();
}
示例9: randomDate
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
/**
* Génère une date entre dans l'intervalle d'année spécifier.
* @param startYear L'année de départ de l'intervalle
* @param endYear l'année de fin de l'intervalle
* @return La date généré
*/
protected Date randomDate(Integer startYear, Integer endYear) {
ThreadLocalRandom random = ThreadLocalRandom.current();
int month = random.nextInt(1, 12);
int day = 1;
if (month == GregorianCalendar.FEBRUARY) {
day = random.nextInt(1, 28);
} else if (month == GregorianCalendar.APRIL || month == GregorianCalendar.JUNE || month == GregorianCalendar.SEPTEMBER || month == GregorianCalendar.OCTOBER) {
day = random.nextInt(1, 30);
} else {
day = random.nextInt(1, 31);
}
GregorianCalendar gc = new GregorianCalendar(random.nextInt(startYear, endYear), random.nextInt(1, 12), day);
return gc.getTime();
}
示例10: twoDiceThrows
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
private static IntFunction<Integer> twoDiceThrows() {
return i -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
int firstThrow = random.nextInt(1, 7);
int secondThrow = random.nextInt(1, 7);
return firstThrow + secondThrow;
};
}
开发者ID:jinyi233,项目名称:https-github.com-RichardWarburton-java-8-Lambdas-exercises,代码行数:9,代码来源:DiceRolls.java
示例11: randomMetric
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
public static Metric randomMetric(int numMetrics, int numDimensions, int numLabels) {
ThreadLocalRandom r = ThreadLocalRandom.current();
int i = r.nextInt(0, numMetrics);
int[] labs = new int[numDimensions];
for (int j = 0; j < numDimensions; j++) {
labs[j] = r.nextInt(0, numLabels);
}
return metric(i, labs);
}
示例12: submitWork
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
public QueryId submitWork(UserClientConnection connection, RunQuery query) {
ThreadLocalRandom r = ThreadLocalRandom.current();
// create a new queryid where the first four bytes are a growing time (each new value comes earlier in sequence). Last 12 bytes are random.
long time = (int) (System.currentTimeMillis()/1000);
long p1 = ((Integer.MAX_VALUE - time) << 32) + r.nextInt();
long p2 = r.nextLong();
QueryId id = QueryId.newBuilder().setPart1(p1).setPart2(p2).build();
incrementer.increment(connection.getSession());
Foreman foreman = new Foreman(bee, bee.getContext(), connection, id, query);
bee.addNewForeman(foreman);
return id;
}
示例13: testNextIntBoundNonPositive
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
/**
* nextInt(non-positive) throws IllegalArgumentException
*/
public void testNextIntBoundNonPositive() {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int bound : new int[] { 0, -17, Integer.MIN_VALUE }) {
try {
rnd.nextInt(bound);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
示例14: shuffle
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
static void shuffle(Object[] keys) {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int size = keys.length;
for (int i=size; i>1; i--) {
int r = rnd.nextInt(i);
Object t = keys[i-1];
keys[i-1] = keys[r];
keys[r] = t;
}
}
示例15: testTraversalEquivalence
import java.util.concurrent.ThreadLocalRandom; //导入方法依赖的package包/类
/**
* Various ways of traversing a collection yield same elements
*/
public void testTraversalEquivalence() {
Collection c = impl.emptyCollection();
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int n = rnd.nextInt(6);
for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
ArrayList iterated = new ArrayList();
ArrayList iteratedForEachRemaining = new ArrayList();
ArrayList tryAdvanced = new ArrayList();
ArrayList spliterated = new ArrayList();
ArrayList splitonced = new ArrayList();
ArrayList forEached = new ArrayList();
ArrayList streamForEached = new ArrayList();
ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
ArrayList removeIfed = new ArrayList();
for (Object x : c) iterated.add(x);
c.iterator().forEachRemaining(iteratedForEachRemaining::add);
for (Spliterator s = c.spliterator();
s.tryAdvance(tryAdvanced::add); ) {}
c.spliterator().forEachRemaining(spliterated::add);
{ // trySplit returns "strict prefix"
Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
if (s2 != null) s2.forEachRemaining(splitonced::add);
s1.forEachRemaining(splitonced::add);
}
c.forEach(forEached::add);
c.stream().forEach(streamForEached::add);
c.parallelStream().forEach(parallelStreamForEached::add);
c.removeIf(e -> { removeIfed.add(e); return false; });
boolean ordered =
c.spliterator().hasCharacteristics(Spliterator.ORDERED);
if (c instanceof List || c instanceof Deque)
assertTrue(ordered);
HashSet cset = new HashSet(c);
assertEquals(cset, new HashSet(parallelStreamForEached));
if (ordered) {
assertEquals(iterated, iteratedForEachRemaining);
assertEquals(iterated, tryAdvanced);
assertEquals(iterated, spliterated);
assertEquals(iterated, splitonced);
assertEquals(iterated, forEached);
assertEquals(iterated, streamForEached);
assertEquals(iterated, removeIfed);
} else {
assertEquals(cset, new HashSet(iterated));
assertEquals(cset, new HashSet(iteratedForEachRemaining));
assertEquals(cset, new HashSet(tryAdvanced));
assertEquals(cset, new HashSet(spliterated));
assertEquals(cset, new HashSet(splitonced));
assertEquals(cset, new HashSet(forEached));
assertEquals(cset, new HashSet(streamForEached));
assertEquals(cset, new HashSet(removeIfed));
}
if (c instanceof Deque) {
Deque d = (Deque) c;
ArrayList descending = new ArrayList();
ArrayList descendingForEachRemaining = new ArrayList();
for (Iterator it = d.descendingIterator(); it.hasNext(); )
descending.add(it.next());
d.descendingIterator().forEachRemaining(
e -> descendingForEachRemaining.add(e));
Collections.reverse(descending);
Collections.reverse(descendingForEachRemaining);
assertEquals(iterated, descending);
assertEquals(iterated, descendingForEachRemaining);
}
}