【发布时间】:2012-05-16 23:04:13
【问题描述】:
配置文件
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() {
}
}
【问题讨论】:
-
在构造函数中传递每个线程的开始和结束编号,或者在线程中添加一个方法来接受范围。
标签: java multithreading