java java中的Executor服务-->单线程代码如何转换为使用executor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14918706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:51:04  来源:igfitidea点击:

Executor service in java--> how to convert single thread code to use executor

javamultithreadingthreadpoolexecutorservice

提问by Arvind

Pardon me if the question sounds silly - I am just starting to use Executor.

如果这个问题听起来很愚蠢,请原谅我 - 我刚刚开始使用 Executor。

I have an existing java app that uses threads in this manner-- basically standalone threads are used--

我有一个以这种方式使用线程的现有 Java 应用程序——基本上使用了独立线程——

private Thread spawnThread( )
    {

        Thread t = new Thread()
        {
            String taskSnap = task.toString();
            public void run()
            {
                try
                {
                    println( task.run( null ) );
                }catch( InterruptedException e )
                {
                    println( "ITC - " + taskSnap + " interrupted " );
                }
            }
        };
        return t;
    }

As you can see from above, the function returns a new thread.

从上面可以看出,该函数返回一个新线程。

Now in the main() function of the program, a new thread is created in this manner--

现在在程序的 main() 函数中,以这种方式创建了一个新线程——

    taskThread = spawnThread();

    taskThread.start();

What i want to do is, create an executor service (with fixed number of threads)--> and then hand off creation of new thread/execution of task by the new thread to that executor.

我想要做的是,创建一个执行程序服务(具有固定数量的线程)--> 然后将新线程的新线程创建/任务执行移交给该执行程序。

As I am very new to Executor, what I wish to know is, how do I change the above code so that instead of a new separate thread being formed, a new thread is instead created within the thread pool. I cannot see any command to create a thread (within the thread pool)--> hand off the above task to that thread (and not to a stand-alone thread as above).

由于我对 Executor 非常陌生,我想知道的是,如何更改上述代码,以便在线程池中创建一个新线程,而不是形成一个新的单独线程。我看不到任何创建线程的命令(在线程池中)--> 将上述任务移交给该线程(而不是上述的独立线程)。

Please let me know how to resolve this problem.

请让我知道如何解决这个问题。

回答by assylias

In your main, you can write something like this:

在你的 main 中,你可以这样写:

ExecutorService executor = Executors.newFixedThreadPool(nThreads);
executor.submit(new Runnable() {
    String taskSnap = task.toString();
    public void run() {
            try {
                println(task.run(null));
            } catch( InterruptedException e) {
                println("ITC - " + taskSnap + " interrupted ");
            }
    }
});

The submit method will execute the Runnable on one of the threads within the executor service.

submit 方法将在执行程序服务中的线程之一上执行 Runnable。

Note: Don't forget to shutdown the executor service when you don't need it any more or it will prevent your program from exiting.

注意:当您不再需要执行程序服务时,请不要忘记关闭它,否则它会阻止您的程序退出。

回答by zengr

Do your research before asking. The idea is to create a class which implements Runnable and execute it using executor service.

在询问之前先做研究。这个想法是创建一个实现 Runnable 的类并使用执行程序服务执行它。

Example from: Java Concurrency (Multithreading) - Tutorial

示例来自:Java 并发(多线程)-教程

Implementation of the worker (which implements Runnable):

worker 的实现(实现了 Runnable):

package de.vogella.concurrency.threadpools;

/** * MyRunnable will count the sum of the number from 1 to the parameter * countUntil and then write the result to the console. * <p> * MyRunnable is the task which will be performed * * @author Lars Vogel * */

public class MyRunnable implements Runnable {
  private final long countUntil;

  MyRunnable(long countUntil) {
    this.countUntil = countUntil;
  }

  @Override
  public void run() {
    long sum = 0;
    for (long i = 1; i < countUntil; i++) {
      sum += i;
    }
    System.out.println(sum);
  }
} 

How to use executor service to run trigger the worker thread.

如何使用执行器服务运行触发工作线程。

package de.vogella.concurrency.threadpools;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
  private static final int NTHREDS = 10;

  public static void main(String[] args) {
    //You can also use Executors.newSingleThreadExecutor() if you just need 1 thread
    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    for (int i = 0; i < 500; i++) {
      Runnable worker = new MyRunnable(10000000L + i);
      executor.execute(worker);
    }
    // This will make the executor accept no new threads
    // and finish all existing threads in the queue.
    executor.shutdown();
    // Wait until all threads are finish
    //while (!executor.isTerminated()) {
    //}
    //System.out.println("Finished all threads");
    //All the threads might not be finished at this point of time. Thread endtime purely depends on the time taken by the processing logic inside your thread.
  }
} 

回答by Axel

You mean something like this?

你的意思是这样的?

class Parallel {
    private ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public void shutdown() {
        pool.shutdown();
    }

    public void foo() {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                // put your code here
            }
        });
    }
}