是否可以使用多线程而无需一遍又一遍地创建线程? [英] Is it possible to use multithreading without creating Threads over and over again?

查看:25
本文介绍了是否可以使用多线程而无需一遍又一遍地创建线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,再次感谢所有已经回答了我的问题的人.我不是一个非常有经验的程序员,这是我第一次体验多线程.

First and once more, thanks to all that already answered my question. I am not a very experienced programmer and it is my first experience with multithreading.

我得到了一个与我的问题非常相似的示例.我希望它可以缓解我们的情况.

I got an example that is working quite like my problem. I hope it could ease our case here.

public class ThreadMeasuring {
private static final int TASK_TIME = 1; //microseconds
private static class Batch implements Runnable {
    CountDownLatch countDown;
    public Batch(CountDownLatch countDown) {
        this.countDown = countDown;
    }

    @Override
    public void run() {         
        long t0 =System.nanoTime();
        long t = 0;
        while(t<TASK_TIME*1e6){ t = System.nanoTime() - t0; }

        if(countDown!=null) countDown.countDown();
    }
}

public static void main(String[] args) {
    ThreadFactory threadFactory = new ThreadFactory() {
        int counter = 1;
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "Executor thread " + (counter++));
            return t;
        }
    };

  // the total duty to be divided in tasks is fixed (problem dependent). 
  // Increase ntasks will mean decrease the task time proportionally. 
  // 4 Is an arbitrary example.
  // This tasks will be executed thousands of times, inside a loop alternating 
  // with serial processing that needs their result and prepare the next ones.
    int ntasks = 4; 
    int nthreads = 2;
    int ncores = Runtime.getRuntime().availableProcessors();
    if (nthreads<ncores) ncores = nthreads;     

    Batch serial = new Batch(null);
    long serialTime = System.nanoTime();
    serial.run();
    serialTime = System.nanoTime() - serialTime;

    ExecutorService executor = Executors.newFixedThreadPool( nthreads, threadFactory );
    CountDownLatch countDown = new CountDownLatch(ntasks);

    ArrayList<Batch> batches = new ArrayList<Batch>();
    for (int i = 0; i < ntasks; i++) {
        batches.add(new Batch(countDown));
    }

    long start = System.nanoTime();
    for (Batch r : batches){
        executor.execute(r);
    }

    // wait for all threads to finish their task
    try {
        countDown.await();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    long tmeasured = (System.nanoTime() - start);

    System.out.println("Task time= " + TASK_TIME + " ms");
    System.out.println("Number of tasks= " + ntasks);
    System.out.println("Number of threads= " + nthreads);
    System.out.println("Number of cores= " + ncores);
    System.out.println("Measured time= " + tmeasured);
    System.out.println("Theoretical serial time= " + TASK_TIME*1000000*ntasks);
    System.out.println("Theoretical parallel time= " + (TASK_TIME*1000000*ntasks)/ncores);
    System.out.println("Speedup= " + (serialTime*ntasks)/(double)tmeasured);

    executor.shutdown();
}
 }

每个批次只是等待给定的时间,而不是进行计算.程序计算加速,理论上总是2,但如果TASK_TIME"很小,可以得到小于1(实际上减速).

Instead of doing the calculations, each batch just waits for some given time. The program calculates the speedup, that would allways be 2 in theory but can get less than 1 (actually a speed down) if the 'TASK_TIME' is small.

我的计算需要前 1 毫秒,而且通常更快.在 1 毫秒内,我发现速度提高了 30% 左右,但实际上,在我的程序中,我发现速度下降.

My calculations take at the top 1 ms and are commonly faster. For 1 ms I find a little speedup of around 30%, but in practice, with my program, I notice a speed down.

此代码的结构与我的程序非常相似,因此如果您能帮助我优化线程处理,我将不胜感激.

The structure of this code is very similar to my program, so if you could help me to optimise the thread handling I would be very grateful.

亲切的问候.

下面是原始问题:

嗨.

我想在我的程序中使用多线程,因为我相信它可以大大提高其效率.它的大部分运行时间是由于独立计算.

I would like to use multithreading on my program, since it could increase its efficiency considerably, I believe. Most of its running time is due to independent calculations.

我的程序有数千个独立的计算(要解决几个线性系统),但它们只是由几十个左右的小群体同时发生.每个组都需要几毫秒才能运行.在其中一组计算之后,程序必须顺序运行一段时间,然后我必须再次求解线性系统.

My program has thousands of independent calculations (several linear systems to solve), but they just happen at the same time by minor groups of dozens or so. Each of this groups would take some miliseconds to run. After one of these groups of calculations, the program has to run sequentially for a little while and then I have to solve the linear systems again.

实际上,可以将这些要求解的独立线性系统视为在迭代数千次的循环中,交替进行依赖于先前结果的顺序计算.我加速程序的想法是在并行线程中计算这些独立计算,方法是将每个组划分为(我可用的处理器数量)独立计算批次.因此,原则上根本不需要排队.

Actually, it can be seen as these independent linear systems to solve are inside a loop that iterates thousands of times, alternating with sequential calculations that depends on the previous results. My idea to speed up the program is to compute these independent calculations in parallel threads, by dividing each group into (the number of processors I have available) batches of independent calculation. So, in principle, there isn't queuing at all.

我尝试使用 FixedThreadPool 和 CachedThreadPool,它甚至比串行处理还要慢.每次我需要解决批次问题时,似乎都需要花费太多时间来创建新的胎面.

I tried using the FixedThreadPool and CachedThreadPool and it got even slower than serial processing. It seems to takes too much time creating new Treads each time I need to solve the batches.

有没有更好的方法来处理这个问题?我使用的这些池似乎适用于每个线程花费更多时间而不是数千个较小线程的情况...

Is there a better way to handle this problem? These pools I've used seem to be proper for cases when each thread takes more time instead of thousands of smaller threads...

谢谢!最好的问候!

推荐答案

从我读到的内容来看:成千上万的独立计算......同时发生......运行需要几毫秒"它似乎是我认为您的问题非常适合 GPU 编程.

From what i've read: "thousands of independent calculations... happen at the same time... would take some miliseconds to run" it seems to me that your problem is perfect for GPU programming.

我认为它回答了你的问题.GPU 编程正变得越来越流行.有用于 CUDA & 的 Java 绑定OpenCL.如果你可以使用它,我说去吧.

And i think it answers you question. GPU programming is becoming more and more popular. There are Java bindings for CUDA & OpenCL. If it is possible for you to use it, i say go for it.

这篇关于是否可以使用多线程而无需一遍又一遍地创建线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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