无法找到如何使用线程池?

时间:2014-04-22 05:27:31

标签: java multithreading

所以,我必须为一个使用Thread的项目修改BankServer java类,我需要用thread pool替换它。但是线程池的教程非常混乱,没有人指定如何创建线程池。 作为参考继承我正在修改

的事情
public static void main(String[] args) throws IOException
{  ArrayList accountList;
  final int ACCOUNTS_LENGTH = 10;
  Bank bank = new Bank(ACCOUNTS_LENGTH);
  final int SBAP_PORT = 8888;
  ServerSocket server = new ServerSocket(SBAP_PORT);
  System.out.println("Waiting for clients to connect...");

  while (true)
  {
     Socket s = server.accept();
     System.out.println("Client connected.");
     BankService service = new BankService(s, bank);
     Thread t = new Thread(service);
     t.start();
  }

我不需要做任何花哨的事情只需将thread改为thread pool,但如果有一个简单的类叫我无法找到它

3 个答案:

答案 0 :(得分:0)

您正在寻找的是ExecutorService

这是一个简单的例子:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledRunnable
{
    public static void main(final String[] args)
    {
        final int numTasks = 10;
        final ScheduledExecutorService ses = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
        for (int i = 0; i < numTasks; i++)
        {
            ses.scheduleAtFixedRate(new MyRunnable(i), 0, 10, TimeUnit.SECONDS);
        }
    }

    private static class MyRunnable implements Runnable
    {
        private int id;
        private int numRuns;

        private MyRunnable(final int id)
        {
            this.id = id;
            this.numRuns = 0;
        }

        @Override
        public void run()
        {
            this.numRuns += 1;
            System.out.format("%d - %d\n", this.id, this.numRuns);
        }
    }
}

此示例使用ScheduleExecutorService还有更多不同的实现,可以针对不同的情况执行不同的操作。

2004年,ExecutorService被添加到JDK中,1.5只用非常少的代码优雅地解决了一个相当复杂但常见的问题。

答案 1 :(得分:0)

如果你搜索并阅读一些例子,那就太容易了。

public static void main(String[] args) throws IOException {
  ArrayList accountList;
  final int ACCOUNTS_LENGTH = 10;
  Bank bank = new Bank(ACCOUNTS_LENGTH);
  final int SBAP_PORT = 8888;
  ServerSocket server = new ServerSocket(SBAP_PORT);
  System.out.println("Waiting for clients to connect...");
  ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_THREAD);

  while (BREAK_CONDITION) {
     Socket s = server.accept();
     System.out.println("Client connected.");
     BankService service = new BankService(s, bank);
     executor.execute(service);
  }
  executor.shutdown();
  while (!executor.isTerminated()) { }
}

另请参阅:Thread PoolsJava Thread Pool Example using Executors and ThreadPoolExecutor

答案 2 :(得分:0)

ThreadPool只是一组工作线程。工作线程是可以重用的线程。 通常,当Thread完成处理其中的代码时,无法重新启动它。这就是我们使用工作线程的原因。 (所以我们不需要为那些可能长时间没有运行的任务创建新的线程对象)

ExecutorService为您提供了不同类型的ThreadPools。以下是他们的一些基本内容:

Executor.newFixedThreadPool(50); //create Thread Pool with 50 worker threads
Executor.newSingleThreadExecutor(); //creates 1 worker thread
Executor.newCachedThreadPool(); //reuses already existing worker threads, but creates them as needed

使用一个的例子:

class App {
     private static ExecutorService executor = Executors.newSingleThreadExecutor();

     public static void main(String[] args) {
          executor.execute(mycode); //instead of creating new thread and adding it, then starting
     }

     private Runnable mycode = new Runnable() {
          public void run() {

          }
     };
}