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)。
有人能告訴我如何將我的順序代碼轉換爲線程安全的 - 請使用一個?
您是否嘗試過'CompletableFuture'並查看它是否適合您的情況?如果你感覺真的很冒險,你總是可以使用一個對象池。 – svarog
@svarog:我忘了說我使用java7 ... – Francesco
在Java 7中,您可以使用線程池或執行程序,java自帶了幾個實現。 – svarog