0

我不确定这样的代码是否安全。我需要从数据库中读取一个名称,我需要使用,比如说 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 )在这种情况下是否足够。

4

2 回答 2

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 而不是循环。

要使用的线程数取决于几个因素:机器、要执行的任务数、任务的“大小”等。

于 2012-07-09T05:03:34.480 回答
0

如果您担心的话,您的第一个循环没有任何线程不安全的地方。我唯一关心的是您使用该Counter变量的目的:您知道您不能依赖它在您MyRunnable的 s 中的值,对吗?

于 2012-07-09T04:59:40.493 回答