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

时间:2012-05-16 23:04:13

标签: java multithreading

配置文件

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() {

    }
}

1 个答案:

答案 0 :(得分:4)

每个帖子都有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

...