2016-03-08 40 views
0

我必須說我有veeery在線程工作的經驗,如果有人能幫助我,我將不勝感激。我有這樣一段代碼基本上詢問位於房間的所有機器的狀態:代碼從順序到線程

private List<ListRow> fetchListRows(Model amtRoomMachinesListModel) 
{ 
    Room room = RoomHelper.getRoomByDbId(...); 

    List<ListRow> listRows = new ArrayList<>(); 

    for (Machine machine : room.getRoomPCs()) 
    { 
     setMachineStatus(machine); 

     if (amtRoomMachinesListModel.getState() == null 
       || amtRoomMachinesListModel.getState().equalsIgnoreCase(machine.getState().getLabel())) 
     { 
      ListRow listRow = new ListRow(false, machine); 

      listRows.add(listRow); 
     } 
    } 

    sortListRows(listRows); 

    return listRows; 
} 


private void setMachineStatus(Machine machine) 
{ 
    State retrievedMachineState = State.ERROR; 
    String machineName = ""; 

    try 
    { 
     machineName = AMTCHelper.ip2MachineName(machine); // executes a nslookup 

     retrievedMachineState = AMTCHelper.retriveMachineState(retrievedMachineState, machineName); // executes an external C program and read the response 
    } 
    catch (IOException | InterruptedException | ParseException e) 
    { 
     throw new BRException(ExceptionType.AMTC_ERROR, "command", String.format(AMTCHelper.getRetriveMachineStateCommand(), machineName) , "error", e.getMessage()); 
    } 

    machine.setState(retrievedMachineState); 
} 

至於狀態請求的響應時間爲4至10秒和機器在一個數空間可能超過100個,我認爲使用線程「同時」啓動機器列表上的過程可能會很有用,這樣總體過程時間會明顯縮短。

我忘了說我使用java 7(不是8)。

有人能告訴我如何將我的順序代碼轉換爲線程安全的 - 請使用一個?

+0

您是否嘗試過'CompletableFuture'並查看它是否適合您的情況?如果你感覺真的很冒險,你總是可以使用一個對象池。 – svarog

+0

@svarog:我忘了說我使用java7 ... – Francesco

+0

在Java 7中,您可以使用線程池或執行程序,java自帶了幾個實現。 – svarog

回答

1

正如斯瓦羅格說,有幾個實現,它都與Java 7

java.util.concurrent中,你有例如類執行人,其中規定:在此基礎上

ExecutorService service = Executors.newFixedThreadPool(nbThreads); 

,你可以使用java.util.concurrent.Future

for (Machine machine : room.getRoomPCs()) 
{ 
    Callable<State> process = new Callable<Integer>() { 
     //whatever you do to retrieve the state 
     return state; 
    } 

    // At this point, the process begins if a thread is available 
    Future<State> future = service.submit(process); 
} 

的過程跑submit()。你可以通過這種方式創建一份期貨清單。當您致電future.get()時,主線程會掛起,直到您收到響應。

最後,我建議你看看番石榴,有很多非常有用的功能。例如,向Future添加回調(onsuccess,錯誤)。