I am not sure whether such code is safe or not. I need to read a name from the DB, and I need to use, say 10 threads, each one take a name, then inside the run it calls a function that needs this name as an argument.
Is 10 threads a suitable number for pc running Intel core i7 with 8GB RAM ?? How can I know the acceptable number of threads I can create? Is this code correct and safe?
I find in Dietel book that they create new thread before the Executor. They add line like: PrintTask task1 = new PrintTask( "thread1" );
check: http://www.deitel.com/articles/java_tutorials/20051126/JavaMultithreading_Tutorial_Part4.html) , but find the below method (without the new statement) in: http://www.vogella.com/articles/JavaConcurrency/article.html
In other word, should I create them before the loop? Two references use different methods and I’m confused. Which code is correct, this:
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");
Also, in the constructor of MyRunnable class that implements run, do i have to start the thread explicitly or does the Executor.execute( worker ) enough in this case.
I would have rewritten it like that:
variable in lower case, awaitTermination instead of a loop.
The number of threads to use depends on several factors: the machine, the number of tasks to execute, the “size” of the task, etc.