我不確定這樣的代碼是否安全。我需要從DB中讀取一個名稱,並且我需要使用10個線程,每個名稱都帶一個名稱,然後在run
內部調用一個需要此名稱作爲參數的函數。在循環中創建線程的正確性
是10個線程適合運行英特爾酷睿i7 8GB內存的電腦?我如何知道我可以創建的可接受的線程數?這段代碼是正確和安全的嗎?
我在Dietel的書中發現,他們在Executor之前創建了新的線程。他們添加一行:PrintTask task1 = new PrintTask("thread1");
檢查:http://www.deitel.com/articles/java_tutorials/20051126/JavaMultithreading_Tutorial_Part4.html),但發現在下面的方法(沒有新的說法):http://www.vogella.com/articles/JavaConcurrency/article.html
換句話說,我應該在循環之前創建它們?兩個引用使用不同的方法,我很困惑。其代碼是正確的做法是:
ExecutorService Executor = Executors.newFixedThreadPool(10);
while(resultSet.next())
{
name=resultSet.getString("hname");
MyRunnable worker = new MyRunnable(name);
Executor.execute(worker);
Counter++;
}
Executor.shutdown();
System.out.println("thread shutdown");
// Wait until all threads are finish
while (! Executor.isTerminated()) {
}
System.out.println("Finished all threads");
OR
MyRunnable task1 = new MyRunnable(name);
MyRunnable task2 = new MyRunnable(name);
MyRunnable task3 = new MyRunnable(name);
MyRunnable task4 = new MyRunnable(name);
MyRunnable task5 = new MyRunnable(name);
MyRunnable task6 = new MyRunnable(name);
MyRunnable task7 = new MyRunnable(name);
MyRunnable task8 = new MyRunnable(name);
MyRunnable task9 = new MyRunnable(name);
MyRunnable task10 = new MyRunnable(name);
ExecutorService Executor = Executors.newFixedThreadPool(10);
while(resultSet.next())
{
name=resultSet.getString("hname");
MyRunnable worker = new MyRunnable(name);
Executor.execute(worker);
Counter++;
}
Executor.shutdown();
System.out.println("thread shutdown");
// Wait until all threads are finish
while (! Executor.isTerminated()) {
}
System.out.println("Finished all threads");
而且,在實現運行MyRunnable類的構造函數,我一定要明確地啓動線程或是否Executor.execute(worker)
足夠在這種情況下, 。
的可運行是*不*線程。他們只是有一個運行方法,告訴線程將最終執行它該做什麼。是的,Executor負責啓動和停止線程。 – Thilo 2012-07-09 04:42:17
'MyRunnable.shutdown()'做了什麼?你的意思是'Executor.shutdown()'? – Thilo 2012-07-09 04:43:10
@Thilo:是的,它應該是'Executor.shutdown'。現在更正。 – 2012-07-09 04:52:01