示例代码:
public class ThreadTest{
public static void main(String ...arg){
try{
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for(int i=0; i < noOfTask; i++){
executor.execute(new ImplRunnable(connectionPool.getConnection()));
}
executor.shutdown();
//Wait for all threads completion
executor.awaitTermination(100, TimeUnit.MICROSECONDS);
}catch(Exception e){
e.printStackTrace();
}finally{
//close database connections etc.
}
}
}
class ImplRunnable implements Runnable{
private Connection conn;
public ImplRunnable(Connection conn){
this.conn = conn;
}
public void run(){
try{
for(int i =0; i < 1000000; i++){
counts++;
}
}catch(Exception exception){
exception.printStackTrace();
}finally{
//close all open statements
try{
conn.close();
}catch(Exception exp){
exp.printStackTrace();
}
}
}
}
我的系统有 4 个核心,因此池大小为 4,我有 10 个任务要做
for 循环打开 10 个线程,但一次运行 4 个线程。但问题是当一个线程完成处理时,它会永远处于等待状态,而不是拿起下一个任务进行处理。上面的代码有什么问题?
请建议...