当前位置: 首页>>代码示例>>Java>>正文


Java ThreadLocalRandom类代码示例

本文整理汇总了Java中java.util.concurrent.ThreadLocalRandom的典型用法代码示例。如果您正苦于以下问题:Java ThreadLocalRandom类的具体用法?Java ThreadLocalRandom怎么用?Java ThreadLocalRandom使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ThreadLocalRandom类属于java.util.concurrent包,在下文中一共展示了ThreadLocalRandom类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: RoundRobinOperator

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
public RoundRobinOperator(TunnelProvider tunnelProvider, OperatorContext context, RoundRobinSender config) throws OutOfMemoryException {
  super(config);
  this.config = config;
  this.allocator = context.getAllocator();
  this.handle = context.getFragmentHandle();
  this.stats = context.getStats();

  List<MinorFragmentEndpoint> destinations = config.getDestinations();
  final ArrayListMultimap<NodeEndpoint, Integer> dests = ArrayListMultimap.create();
  for(MinorFragmentEndpoint destination : destinations) {
    dests.put(destination.getEndpoint(), destination.getId());
  }

  this.tunnels = new ArrayList<>();
  this.minorFragments = new ArrayList<>();
  for(final NodeEndpoint ep : dests.keySet()){
    List<Integer> minorsList= dests.get(ep);
    minorFragments.add(minorsList);
    tunnels.add(tunnelProvider.getExecTunnel(ep));
  }

  int destCount = dests.keySet().size();
  this.currentTunnelsIndex = ThreadLocalRandom.current().nextInt(destCount);
  this.currentMinorFragmentsIndex = ThreadLocalRandom.current().nextInt(minorFragments.get(currentTunnelsIndex).size());
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:26,代码来源:RoundRobinOperator.java

示例2: testNextDoubleBounded2

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
/**
 * nextDouble(least, bound) returns least <= value < bound;
 * repeated calls produce at least two distinct results
 */
public void testNextDoubleBounded2() {
    for (double least = 0.0001; least < 1.0e20; least *= 8) {
        for (double bound = least * 1.001; bound < 1.0e20; bound *= 16) {
            double f = ThreadLocalRandom.current().nextDouble(least, bound);
            assertTrue(least <= f && f < bound);
            int i = 0;
            double j;
            while (i < NCALLS &&
                   (j = ThreadLocalRandom.current().nextDouble(least, bound)) == f) {
                assertTrue(least <= j && j < bound);
                ++i;
            }
            assertTrue(i < NCALLS);
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:ThreadLocalRandomTest.java

示例3: getRandomImageLinkForImgurId

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
/**
 * Get an image link from an imgur album
 * @param albumId Album ID
 * @return Link to an image
 * @throws NoAPIKeyException No imgur key setup
 */
public static String getRandomImageLinkForImgurId(String albumId) throws NoAPIKeyException {
	try {
		URL url = new URL(String.format("https://api.imgur.com/3/album/%s/images", albumId));
		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		urlConnection.setRequestProperty("Authorization", "Client-ID "
				+ Bot.getInstance().getApiKeys().get("imgur"));
		urlConnection.connect();
		StringBuilder stb = new StringBuilder();
		// Get the response
		BufferedReader rd = new BufferedReader(
				new InputStreamReader(urlConnection.getInputStream()));
		String line;
		while ((line = rd.readLine()) != null) {
			stb.append(line).append("\n");
		}
		JsonArray ja = Json.parse(stb.toString()).asObject().get("data").asArray();
		int randomInt = ThreadLocalRandom.current().nextInt(0, ja.size());
		String imgurLink = ja.get(randomInt).asObject().get("link").asString();

		return imgurLink;
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
 
开发者ID:paul-io,项目名称:momo-2,代码行数:32,代码来源:Util.java

示例4: testSnapshotFileName

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
@Test
public void testSnapshotFileName() throws Exception {
  final long term = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);
  final long index = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);
  final String name = SimpleStateMachineStorage.getSnapshotFileName(term, index);
  System.out.println("name = " + name);
  final File file = new File(storageDir, name);
  final TermIndex ti = SimpleStateMachineStorage.getTermIndexFromSnapshotFile(file);
  System.out.println("file = " + file);
  Assert.assertEquals(term, ti.getTerm());
  Assert.assertEquals(index, ti.getIndex());
  System.out.println("ti = " + ti);

  final File foo = new File(storageDir, "foo");
  try {
    SimpleStateMachineStorage.getTermIndexFromSnapshotFile(foo);
    Assert.fail();
  } catch(IllegalArgumentException iae) {
    System.out.println("Good " + iae);
  }
}
 
开发者ID:apache,项目名称:incubator-ratis,代码行数:22,代码来源:TestRaftStorage.java

示例5: testDoublesCount

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
/**
 * A parallel sized stream of doubles generates the given number of values
 */
public void testDoublesCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 0;
    for (int reps = 0; reps < REPS; ++reps) {
        counter.reset();
        r.doubles(size).parallel().forEach(x -> {
            counter.increment();
        });
        assertEquals(counter.sum(), size);
        size += 524959;
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:17,代码来源:ThreadLocalRandomTest.java

示例6: testNextLongBounded2

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
/**
 * nextLong(least, bound) returns least <= value < bound; repeated calls
 * produce at least two distinct results
 */
public void testNextLongBounded2() {
    for (long least = -86028121; least < MAX_LONG_BOUND; least += 982451653L) {
        for (long bound = least + 2; bound > least && bound < MAX_LONG_BOUND; bound += Math.abs(bound * 7919)) {
            long f = ThreadLocalRandom.current().nextLong(least, bound);
            assertTrue(least <= f && f < bound);
            int i = 0;
            long j;
            while (i < NCALLS &&
                   (j = ThreadLocalRandom.current().nextLong(least, bound)) == f) {
                assertTrue(least <= j && j < bound);
                ++i;
            }
            assertTrue(i < NCALLS);
        }
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:21,代码来源:ThreadLocalRandomTest.java

示例7: declareNewPartyLeader

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
public void declareNewPartyLeader() throws InsufficientMembersException {
    if (members.size() == 1) {
        throw new InsufficientMembersException(members.size());
    }
    T newPartyLeader = partyLeader;
    while (newPartyLeader.equals(partyLeader)) {
        int pseudoRandomIndex = 
            ThreadLocalRandom.current().nextInt(
                0,
                members.size());
        newPartyLeader = members.get(pseudoRandomIndex);
    }
    partyLeader.speak(
        String.format("%s is our new party leader.", 
            newPartyLeader.getName()));
    newPartyLeader.danceWith(partyLeader);
    if (newPartyLeader.compareTo(partyLeader) < 0) {
        // The new party leader is younger
        newPartyLeader.danceAlone();
    }
    partyLeader = newPartyLeader;
}
 
开发者ID:PacktPublishing,项目名称:Java-9-with-JShell,代码行数:23,代码来源:example10_01.java

示例8: testNextLongBounded2

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
/**
 * nextLong(least, bound) returns least <= value < bound;
 * repeated calls produce at least two distinct results
 */
public void testNextLongBounded2() {
    for (long least = -86028121; least < MAX_LONG_BOUND; least += 982451653L) {
        for (long bound = least + 2; bound > least && bound < MAX_LONG_BOUND; bound += Math.abs(bound * 7919)) {
            long f = ThreadLocalRandom.current().nextLong(least, bound);
            assertTrue(least <= f && f < bound);
            int i = 0;
            long j;
            while (i < NCALLS &&
                   (j = ThreadLocalRandom.current().nextLong(least, bound)) == f) {
                assertTrue(least <= j && j < bound);
                ++i;
            }
            assertTrue(i < NCALLS);
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:ThreadLocalRandomTest.java

示例9: newDeck

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
public void newDeck(){
	currentIndex=0;
	List<Integer> usedSlots = new ArrayList<>();
	List<Card> originDeck = Card.newOrderedDeck();
	cardsInDeck = new Card[52];
	Random r = ThreadLocalRandom.current();
	
	//Shuffle
	for(int i = 0; i < originDeck.size();i++){
		int newGoodIndex = r.nextInt(cardsInDeck.length);
		while(true){
		if(usedSlots.contains(newGoodIndex)){
			newGoodIndex=(newGoodIndex+1)%originDeck.size();
		}else{
			usedSlots.add(newGoodIndex);
			cardsInDeck[newGoodIndex] = originDeck.get(i);
			break;
		}
		}
	}
}
 
开发者ID:ZombieStriker,项目名称:NeuralNetworkAPI,代码行数:22,代码来源:QuickBlackJackHandler.java

示例10: testIteratorRandomRemoveHighVolume

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
@Test
public void testIteratorRandomRemoveHighVolume() throws InterruptedException {
    RMapCache<Integer, Integer> map = redisson.getMapCache("simpleMap");
    for (int i = 0; i < 10000; i++) {
        map.put(i, i*10);
    }
    
    int cnt = 0;
    int removed = 0;
    Iterator<Entry<Integer, Integer>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Entry<Integer, Integer> entry = iterator.next();
        if (ThreadLocalRandom.current().nextBoolean()) {
            iterator.remove();
            removed++;
        }
        cnt++;
    }
    Assert.assertEquals(10000, cnt);
    assertThat(map.size()).isEqualTo(cnt - removed);
}
 
开发者ID:qq1588518,项目名称:JRediClients,代码行数:22,代码来源:RedissonMapCacheTest.java

示例11: testSortedSetAddRemove

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
@Test
public void testSortedSetAddRemove() throws Exception {
  int rnd = ThreadLocalRandom.current().nextInt(0, presetElements.size());
  String key = presetElementKeys.get(rnd);
  String value = String.valueOf(presetElements.get(key));

  Snapshot snapshot = tracker.snapshot();
  snapshot.increment("zadd");
  Long added = jedis.zadd(key, 1, value);
  assertEquals(1, (long) added);

  snapshot.increment("zrem");
  Long removed = jedis.zrem(key, value);
  assertEquals(1, (long) removed);
  snapshot.validate();
}
 
开发者ID:ApptuitAI,项目名称:JInsight,代码行数:17,代码来源:JedisInstrumentationTest.java

示例12: onEventReceived

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
@Override
public Object onEventReceived(IDevice device) {
	String senderNumber = "";
	for(int i = 0; i < 8; i++)
		senderNumber += ThreadLocalRandom.current().nextInt(0, 9 + 1);
	
	EmulatorConsole emulatorConsole = EmulatorConsole.getConsole(device);
	LoggerHelper.logEvent(MyLevel.ADB_EVENT, adbEventFormat(toString(), String.format("incomingCall(%s)", senderNumber)));
	//call a random number
	emulatorConsole.call(senderNumber);
	//let it ring for 3 seconds
	try {
		Thread.sleep(3000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	//cancel call
	emulatorConsole.cancelCall(senderNumber);
	return null;
}
 
开发者ID:srasthofer,项目名称:FuzzDroid,代码行数:21,代码来源:IncomingCallEvent.java

示例13: handleCoinToss

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
private void handleCoinToss(@NotNull MessageReceivedEvent event, @NotNull List<String> args) {
    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 = 0;
    ThreadLocalRandom random = ThreadLocalRandom.current();
    EmbedBuilder builder = MessageUtils.getEmbedBuilder(event.getMessage().getAuthor());
    int heads = 0;
    int tails = 0;
    while (sIterations++ != iterations) {
        boolean res = random.nextBoolean();

        if (res) heads++;
        else tails++;

        builder.appendField("Round " + (sIterations), res ? "Head" : "Tail", true);
    }
    builder.withTitle("Tossed " + (sIterations - 1) + (sIterations == 1 ? " coin" : " coins"));
    builder.withDescription("Heads: " + heads + ". Tails: " + tails);

    sendThenDelete(MessageUtils.getMessageBuilder(event.getMessage())
            .withEmbed(builder.build()));
    delete(event.getMessage());
}
 
开发者ID:ViniciusArnhold,项目名称:ProjectAltaria,代码行数:26,代码来源:RandomNumberCommand.java

示例14: main

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
public static void main(String[] args){
    byte[] sourceAddress = new byte[20];        
    //Random random = new Random(); 
    //random.nextBytes(sourceAddress);
    ThreadLocalRandom.current().nextBytes(sourceAddress);
    
    byte[] publicKey = new byte[120];
    ThreadLocalRandom.current().nextBytes(publicKey);
    
    UnsignedTransaction unsignedTransaction = new UnsignedTransaction(sourceAddress, 
            RandomTransactionProvider.createAddressesAndAmounts(2), publicKey);
    log.info("Unsigned transaction: " + unsignedTransaction);
    byte[] bytes = Serializer.serialize(unsignedTransaction);
    log.info("Serialization bytes: " + Arrays.toString(bytes));
    log.info("Serialization bytes length: " + bytes.length);
    
    UnsignedTransaction deserializedUT = Deserializer.createObject(bytes, UnsignedTransaction.class);
    log.info("\nDeserialized unsigned transaction: " + deserializedUT);
    log.info("Are the two unsigned transactions equal?: " + unsignedTransaction.equals(deserializedUT));        
}
 
开发者ID:VictorGil,项目名称:shared-ledger-simulator,代码行数:21,代码来源:SerializationTester.java

示例15: getDrops

import java.util.concurrent.ThreadLocalRandom; //导入依赖的package包/类
@Override
public Item[] getDrops(Item item) {
    if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) {
        int count = 1;
        Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING);
        if (fortune != null && fortune.getLevel() >= 1) {
            int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1;

            if (i < 0) {
                i = 0;
            }

            count = i + 1;
        }

        return new Item[]{
                new ItemCoal(0, count)
        };
    } else {
        return new Item[0];
    }
}
 
开发者ID:Rsplwe,项目名称:Nukkit-Java9,代码行数:23,代码来源:BlockOreCoal.java


注:本文中的java.util.concurrent.ThreadLocalRandom类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。