1 我有一个程序需要在for 循环中增加 Runnable,现在发现他执行的顺序是从上往下 ,不是多线程的方式执行
2 代码如下
public void addUserACard() {
ThreadLbData tLbData = null;
DbBean dbBean = null ;
List<DataBase> listData = dataDAO.findHql(" from DataBase where state = '1' order by createDate desc ");
DataBase data = null ;
if(listData != null && listData.size()> 0){
for (int i = 0; i < listData.size(); i++) {
data = listData.get(i);
dbBean = createDbBean(data);
tLbData = new ThreadLbData(dbBean);
tLbData.run();
}
}
}
}
@SuppressWarnings("unchecked")
public class ThreadLbData implements Runnable {
private DbBean dataBase;
private Map map = new HashMap();
private static ConnectionPools connectionPools = ConnectionPools.getInstance();
public ThreadLbData(DbBean dataBase) {
this.dataBase = dataBase;
}
public void run() {
Connection conn = connectionPools.getConnectionOracle(); // 获得JDBC链接;
try {
String lbMaxId = this.getSynLogMaxId(dataBase, conn);
Map map = getLbDate(lbMaxId);
saveAll((List<ReaderCard>) map.get("listCard"), (List<Userinfo>) map.get("listUser"), conn);
} catch (Exception e) {
e.printStackTrace();
}finally{
connectionPools.close(null, null, conn);
}
}
}
3 想让大神帮我看看,线程的run能不能并行,并且帮我改进,跪谢!
黄舟2017-04-18 10:19:32
Use thread pool!
private ExecutorService executorService = Executors.newFixedThreadPool(10);
public void addUserACard() {
ThreadLbData tLbData = null;
DbBean dbBean = null ;
List<DataBase> listData = dataDAO.findHql(" from DataBase where state = '1' order by createDate desc ");
DataBase data = null ;
if(listData != null && listData.size()> 0){
for (int i = 0; i < listData.size(); i++) {
data = listData.get(i);
dbBean = createDbBean(data);
executorService.execute(tLbData);
}
}
}
private ExecutorService executorService = Executors.newFixedThreadPool(10);
The above Executors.newFixedThreadPool(10) creates a thread pool with a fixed size of 10.
Then submit a task through executorService.execute( Runnable runnable), so that a maximum of 10 tasks can be executed in parallel . If more parallel threads are needed, the parameters of Executors.newFixedThreadPool(threadCount) can be set larger.
I want to complain, you must have confused the Runnable interface with the Thread class, right? A class that implements the Runnable interface does not mean that it runs in a new thread. You must explicitly submit the Runnable to the new thread for execution. For example executorService.execute(runnable) or new Thread(runnable).start().
怪我咯2017-04-18 10:19:32
The run method cannot be called directly, the thread must be executed through the Thread.start method. There is no difference between calling the run method directly and calling a normal method.
new Thread(tLbData).start()