在每个线程之间分配数字范围 [英] Distribute Range of Numbers between each threads

查看:108
本文介绍了在每个线程之间分配数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

配置文件

ThreadSize = 10
StartRange = 1
EndRange = 1000

我有一个配置文件,上面有我要使用的线程数,并且客户端实例可以使用ID范围从1到1000,并且假设客户端线程设置为10,因此每个线程都将具有范围可以使用的100个ID(基本上是通过将线程的终止范围除以线程大小),而无需踩踏其他线程.所以我想要的是每个线程应该使用该范围内的100个ID,而不要踩其他线程-例如

I have a config file above in which I have number of threads I want to use and the client instance is able to use ID range from 1 to 1000 and suppose the client threads is set at 10, so each thread would have range of 100 id's(basically by dividing end range with thread size) that it can use without stepping on other threads. so What I want is that each thread should use 100 id's from that range without stepping on other threads- for example

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

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

I know how to write a multithreading program, but not sure how should I divide the range between various threads.

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

Thread i = 0 would get range (1 + 0*100) - (1 + 0*100 + 100 - 1) = 1 - 100

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

Thread i = 1 would get range (1 + 1*100) - (1 + 1*100 + 100 - 1) = 101 - 200

...

这篇关于在每个线程之间分配数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆