在线程之间分配不均数 [英] Divide an uneven number between Threads

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

问题描述

我正在学习Java中的线程,我想按字母顺序对单词列表进行排序.我的程序读取txt文件中的单词,然后将它们放在字符串数组中.用户可以选择自己想使用多少个线程.我想将数组分成偶数个(尽可能多的)块,线程可以自己对它们进行排序.

I am just learning Threads in Java and I want to sort a list of words alphabetical. My program read the words of a txt-file and put them in a String-array. The user can choose how many threads they want to use themselves. I want to split the array in even (as possible) chunks that the threads can sort by themselves.

所以我的问题是

如何在各个线程之间尽可能地拆分array.length?我的脑袋一片空白,我想不出一种聪明的方法来做到这一点.

How can I split the array.length as even as possible across the threads? My mind is blanking and I can't think of a smart way to do this.

例如:如果我的array.length为22和4个线程,在这种情况下如何分配线程; 6、6、5和5个大小的阵列?需要适用于给定的每个数字.

e.g: If I have a array.length of 22 and 4 threads, how can give the threads in this case; 6, 6, 5 and 5 sized pieces of the array? Needs to be applicable to every number given.

我尽力解释了一下,请询问是否不清楚!谢谢!

I tried to explain it the best I could, please ask if something was unclear! Thank you!

推荐答案

它不必尽可能均匀.如果一个线程有6个线程,这将确定所花费的时间,在这种情况下,最多6个线程无关紧要.

It doesn't need to be as evenly as possible. If one thread has 6, this will determine the length of time it takes in which case it doesn't matter how many are up to 6.

你可以做

int chunkSize = (tasks + threads - 1) / threads; // divide by threads rounded up.
for (int t = 0; t < threads; t++) {
    int start = t * chunksSize;
    int end = Math.min(start + chunkSize, tasks);
    executor.submit(() -> {
         // inside the thread
         for (int i = start; i < end; i++) {
             process(i);
    });
}

注意:如果使用Stream.of(array).parallel(),则实际上每个线程创建两个任务.这样可以缓解某些批次即使元素数量相同也可能需要更长的时间.

Note: if you use Stream.of(array).parallel() it actually create two tasks per thread. This mitigates that some batches might take longer even though they have the same number of elements.

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

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