将任务添加到执行程序

时间:2014-01-21 20:47:06

标签: java multithreading executorservice

我编写了一个内部类CreateRecord来创建一个Record实例。当调用create方法时,它稍后作为任务提交给执行者。 我是否必须每次都要创建一个内部类来表示要执行的任务(例如deleteRecord,updateRecord)。 任何人都可以提出更好的方法。

 ExecutorService exec=new ThreadPoolExecutor(corePoolSize,maxPoolSize,
         keepAlive,TimeUnit.MINUTES,new LinkedBlockingQueue<Runnable>());

    public void create(String str ) throws RemoteException
    {
      exec.execute(new CreateRecord(str));
    }

    class CreateRecord implements Runnable
    {
      private String Id;
      public  CreateRecord(String Id)
      {
        this.Id=Id;
      }

      @Override
      public void run() 
      {

        System.out.println("Record creation in progress of: "+Id+
              " by thread: "+Thread.currentThread().getName());
        Record rec=new Record(Id);
        map.put(Id, rec);
      }
    }

3 个答案:

答案 0 :(得分:0)

您可以实例化Runnable而不是声明新类。这些在Java中称为匿名内部类。

public void create(final String id) throws RemoteException
{
    exec.execute(new Runnable()
    {
        @Override
        public void run() 
        {
            System.out.println("Record creation in progress of: "+id+" by thread: "+Thread.currentThread().getName());
            Record rec=new Record(id);
            map.put(id, rec);
        }
    });
}

答案 1 :(得分:0)

ExecutorService需要Runnable个对象。 Runnable对象必须是类的实例。

两个选项:

(1)将您的Runnable课程参数化,以便能够做多件事。但这违反了一些好的设计原则。

(2)使用匿名类:

public void create(final String id) throws RemoteException {
    exec.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Record creation in progress of: "+id+" by thread: "+Thread.currentThread().getName());
            Record rec = new Record(id);
            map.put(id, rec);
        }
    });
}

请注意,id以及您要在Runnable之外使用的任何其他变量必须声明为final

FYI,

System.out.printf(
    "Record creation in progress of: %d by thread: %s%n",
    id,
    Thread.currentThread().getName()
);

更清晰。

答案 2 :(得分:-1)

像现在这样有一个类,比如Record,并在构造函数中指定一个额外的intString参数,可以在run()中使用决定做什么的方法 - 即更新,删除或添加记录,具体取决于第二个参数的值。像这样:

class Record implements Runnable
{
  private String id;
  private String operation;
  public  Record(String id, String operation)
  {
    this.id = id;
    this.operation = operation;
  }

  @Override
  public void run() 
  {
      if(operation.equals("update")) {
          //code for updating
      } else if(operation.equals("insert")) {
          System.out.println("Record creation in progress of: "+Id+
                  " by thread: "+Thread.currentThread().getName());
            Record rec=new Record(id);
            map.put(id, rec);
      } else {//if(operation.equals("delete"))
          map.remove(id);
      }

  }
}