【问题标题】:Executor service in java--> how to convert single thread code to use executorjava中的执行器服务-->如何将单线程代码转换为使用执行器
【发布时间】:2013-02-17 06:50:51
【问题描述】:

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

我有一个以这种方式使用线程的现有 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;
    }

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

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

    taskThread = spawnThread();

    taskThread.start();

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

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

请告诉我如何解决这个问题。

【问题讨论】:

  • 将线程的“运行”部分包装在一个可运行接口中。创建一个 executor 并提供 Runnable 给它。查看Executor 线索了解更多信息

标签: java multithreading threadpool executorservice


【解决方案1】:

在你的 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 ");
            }
    }
});

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

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

【讨论】:

    【解决方案2】:

    提问前先做调查。这个想法是创建一个实现 Runnable 的类并使用执行器服务执行它。

    示例来自:Java Concurrency (Multithreading) - Tutorial

    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);
      }
    } 
    

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

    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.
      }
    } 
    

    【讨论】:

    • 当然,这只是理解线程结构的示例代码。在实际代码中,您不会不必要地等待。
    • 好的,但我担心 SO 示例代码会经常按原样使用“因为它可以正常工作”...
    【解决方案3】:

    你的意思是这样的?

    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
                }
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2016-04-21
      • 1970-01-01
      • 2018-04-12
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多