我不确定这样的代码是否安全。我需要从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