2014-01-21 34 views
1

我編寫了一個用於創建Record實例的內部類CreateRecord。稍後在調用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); 
     } 
    } 

回答

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

    } 
} 
+3

我不太喜歡[stringly typed](http://c2.com/cgi/wiki?StringlyTyped)[命令模式](https://en.wikipedia.org/wiki/Command_pattern )。 – Jeffrey

+0

如果Enum是UPDATE,INSERT和DELETE並且使用switch語句,那麼操作應該是Enum類型。 – mdewitt

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

ExecutorService需要Runnable對象。 A 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() 
); 

有點更清晰。