我不确定这样的代码是否安全。我需要从数据库中读取一个名称,我需要使用,比如说 10 个线程,每个线程都有一个名称,然后在run
它内部调用一个需要这个名称作为参数的函数。
10 个线程是否适合运行 Intel core i7 和 8GB RAM 的电脑?我如何知道我可以创建的可接受的线程数?此代码是否正确且安全?
我在 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/文章.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");
或者
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 )
在这种情况下是否足够。