我不确定这些代码是否安全。我需要从数据库中读取一个名称,我需要使用,比方说10个线程,每个都取一个名字,然后在run
里面调用一个需要这个名字作为参数的函数。
对于运行带有8GB RAM的Intel核心i7的PC,10个线程是否合适?我怎么知道我可以创建的可接受线程数?这段代码是否正确且安全?
我在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");
此外,在实现run的MyRunnable类的构造函数中,我是否必须显式启动线程,或者在这种情况下Executor.execute( worker )
是否足够。
答案 0 :(得分:3)
我会改写它:
ExecutorService executor = Executors.newFixedThreadPool(10);
while(resultSet.next())
{
name=resultSet.getString("hname");
MyRunnable worker = new MyRunnable(name);
executor.submit(worker);
counter++;
}
executor.shutdown();
System.out.println("thread shutdown");
executor.awaitTermination(60, TimeUnit.SECONDS);
System.out.println("Finished all threads");
小写变量,awaitTermination而不是循环。
要使用的线程数取决于几个因素:机器,要执行的任务数,任务的“大小”等。
答案 1 :(得分:0)
对于你的第一个循环,没有任何线程不安全的,如果你担心的话。我唯一关心的是你使用Counter
变量:你知道你不能在MyRunnable
内依赖它的价值,对吗?