我有一个程序,必须处理很多工作 list 。为了加快整个过程,我想实现线程。

我考虑这样的事情:

主类

// I have a joblist with 100 entries
int iAmountThreads = 5;
for(Job oJob : joblist)
{
//only execute 5 Jobs at the same time
        if(Thread.activeCount() < iAmountThreads)
        {
            Runnable threadJob = new JobRunnable(oJob);
            Thread myThread = new Thread(threadJob);
            myThread.start();
        }
    }

//wait here until all jobs from the joblist are finished

可运行类实现可运行
public class JobRunnable implements Runnable
{
     private Job oJob;

     public JobRunnable(Job _oJob)
     {
         oJob = _oJob;

     }

     public void run()
     {
        //processing of the job
     }
}

我正在寻找一种方法来同时运行5个作业,直到处理完整个列表。当一个作业完成时->下一个线程将启动。

谢谢你的帮助!

最佳答案

通过执行程序API使用固定线程池:

Executor executor = Executors.newFixedThreadPool(5);

// all jobs are submitted sequentially, but only 5 jobs execute concurrently at a time
for(Runnable job : jobs)
{
    executor.execute(job);
}

10-04 11:48