3

配置文件

ThreadSize = 10
StartRange = 1
EndRange = 1000

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

    }
}
4

2 回答 2

4

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

线程号i获取 range (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

...

于 2012-05-16T23:06:49.353 回答
0
public class MyThread extends Thread {
    public static final int TOTAL_THREADS = 10;
    public static final int START_RANGE = 1;
    public static final int END_RANGE = 1000;
    public static final int N = (END_RANGE - START_RANGE + 1) / TOTAL_THREADS;
    int threadNo;
    static volatile int counter = 1;
    public final static Object obj = new Object();

    public MyThread(int threadNo) {
        this.threadNo = threadNo;
    }

    @Override
    public void run() {
        synchronized (obj) {
            while (counter <= 1000) {
                if (counter >= (START_RANGE + threadNo * N) && counter <= (START_RANGE + threadNo * N + N - 1)) {
                    System.out.println((this.threadNo + 1) + " prints " + counter++);
                    obj.notifyAll();
                } else {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String args[]) {
        for (int i = 0; i < TOTAL_THREADS; i++) {
            System.out.println("Call thread : " + (i + 1));
            MyThread th = new MyThread(i);
            th.start();
        }
    }
}
于 2022-01-25T18:35:09.157 回答