在Java中,根据线程划分循环执行
假设我有一个方法run,如下所示在Java中,根据线程划分循环执行,java,multithreading,Java,Multithreading,假设我有一个方法run,如下所示 public void run() { for(i=loopstart;i<loopend;i++){ //some code here to execute. no dependency exists } 我想根据线程数将其划分为多个执行范围。 e、 g 这些只是例子(不确切)。我想根据可用线程划分其执行。 因此对于2个线程 thread_start=5 ,thread_end=44 1st thread
public void run()
{
for(i=loopstart;i<loopend;i++){
//some code here to execute. no dependency exists
}
我想根据线程数将其划分为多个执行范围。e、 g 这些只是例子(不确切)。我想根据可用线程划分其执行。
因此对于2个线程
thread_start=5 ,thread_end=44 1st thread
thread_start=45 ,thread_end=94 2nd thread.
我应该如何(使用java代码)在几乎相同的长度范围内划分循环执行 公共类循环器实现可运行{
public class Looper implements Runnable {
private int start;
private int end;
public Looper(int start, int end){
this.start = start;
this.end = end;
}
@Override
public void run() {
for(int i=start; i<end; i++){
System.out.println("thread id : " + Thread.currentThread().getId() + "; index : " + i) ;
}
}
}
public class Test {
public static void main(String[] args){
Thread looper1 = new Thread(new Looper(1,1000));
Thread looper2 = new Thread (new Looper(1001,2000));
looper1.start();
looper2.start();
}
}
私人int启动;
私人互联网终端;
公共活套(int开始,int结束){
this.start=start;
this.end=end;
}
@凌驾
公开募捐{
对于(int i=start;iI强烈建议您查看OpenMP for Java-请参阅示例。这将给出非常优化的代码。@adeel iqbal阅读关于固定线程数的线程池;并将任务添加到队列中。只需计算Thread\u start[k]=loopstart+looprange*k
,其中looprange=(loopend loopstart)/线程数
。确保looprange>0。thread\u end[k]=loopstart+looprange*(k+1)-1
,最后一个线程除外,它等于loopend
。问题是如何找到像1-1000、1001-2000这样的范围,这取决于如何创建这些线程以及创建多少个线程来执行循环。
threads ranges
2 5-44, 45-94
3 5-34, 35-65, 66-94
thread_start=5 ,thread_end=44 1st thread
thread_start=45 ,thread_end=94 2nd thread.
public class Looper implements Runnable {
private int start;
private int end;
public Looper(int start, int end){
this.start = start;
this.end = end;
}
@Override
public void run() {
for(int i=start; i<end; i++){
System.out.println("thread id : " + Thread.currentThread().getId() + "; index : " + i) ;
}
}
}
public class Test {
public static void main(String[] args){
Thread looper1 = new Thread(new Looper(1,1000));
Thread looper2 = new Thread (new Looper(1001,2000));
looper1.start();
looper2.start();
}
}