首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >java中的Executor服务-->如何将单线程代码转换为使用executor

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

Stack Overflow用户
提问于 2013-02-17 14:50:52
回答 3查看 16.1K关注 0票数 7

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

我有一个现有的java应用程序,它以这种方式使用线程--基本上是使用独立的线程--

代码语言:javascript
运行
复制
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()函数中,以这种方式创建了一个新线程--

代码语言:javascript
运行
复制
    taskThread = spawnThread();

    taskThread.start();

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

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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-02-17 14:55:03

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

代码语言:javascript
运行
复制
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方法将在executor服务中的一个线程上执行Runnable。

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

票数 9
EN

Stack Overflow用户

发布于 2013-02-17 14:55:48

在提问之前先做研究。其思想是创建一个实现Runnable的类,并使用executor服务执行它。

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

worker的实现(实现Runnable):

代码语言:javascript
运行
复制
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);
  }
} 

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

代码语言:javascript
运行
复制
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.
  }
} 
票数 5
EN

Stack Overflow用户

发布于 2013-02-17 14:58:10

你是说像这样的东西?

代码语言:javascript
运行
复制
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
            }
        });
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14918706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档