gpt4 book ai didi

java - 在每个线程之间分配数字范围

转载 作者:行者123 更新时间:2023-11-30 07:25:55 26 4
gpt4 key购买 nike

配置文件

ThreadSize = 10
StartRange = 1
EndRange = 1000

我上面有一个配置文件,其中我有我想使用的线程数,客户端实例能够使用从 1 到 1000 的 ID 范围,假设客户端线程设置为 10,所以每个线程都有范围100 个 id(基本上是通过将结束范围除以线程大小),它可以在不踩到其他线程的情况下使用。所以我想要的是每个线程都应该使用该范围内的 100 个 id 而不会踩到其他线程 - 例如

Thread1 will use 1 to 100 (id's)
// generate a random number between 1 to 100 and keep on printing values until it has generated all the random values between 1 to 100
Thread2 will use 101 to 200 (id's)
// generate a random number between 101 to 200 and keep on printing values until it has generated all the random values between 101 to 200
Thread3 will use 201 to 300 (id's)
// generate a random number between 201 to 300 and keep on printing values until it has generated all the random values between 201 to 300

-----
----
Thread10 will use 901 to 1000
// generate a random number between 901 to 1000 and keep on printing values until it has generated all the random values between 901 to 1000

我知道如何编写多线程程序,但不确定如何划分各个线程之间的范围。

public static void main(String[] args) {

for (int i = 1; i <= threadSize; i++) {
new Thread(new ThreadTask(i)).start();
}
}


class ThreadTask implements Runnable {
private int id;

public ThreadTask(int id) {
this.id = id;
}

public synchronized void run() {

}
}

最佳答案

每个线程都得到 N = (EndRange - StartRange + 1)/ThreadSize 数字。

线程号 i 获取范围 (StartRange + i*N) - (StartRange + i*N + N - 1)

在您的示例中 N = (1000 - 1 + 1)/10 = 100

线程 i = 0 将得到范围 (1 + 0*100) - (1 + 0*100 + 100 - 1) = 1 - 100

线程 i = 1 将得到范围 (1 + 1*100) - (1 + 1*100 + 100 - 1) = 101 - 200

...

关于java - 在每个线程之间分配数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10627934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com