fo循环中增加Runnable线程

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能不能并行,并且帮我改进,跪谢!


慕慕森
浏览 616回答 2
2回答

慕仙森

用线程池呗!private ExecutorService executorService = Executors.newFixedThreadPool(10);public void addUserACard() {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; ThreadLbData tLbData = null;&nbsp; &nbsp; DbBean dbBean = null ;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; List<DataBase> listData = dataDAO.findHql(" from DataBase where state = '1'&nbsp; order by createDate desc ");&nbsp; &nbsp; DataBase data = null ;&nbsp; &nbsp; if(listData != null && listData.size()> 0){&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < listData.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data = listData.get(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dbBean =&nbsp; createDbBean(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; executorService.execute(tLbData);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}private ExecutorService executorService = Executors.newFixedThreadPool(10);上面的 Executors.newFixedThreadPool(10) 是创建了一个固定大小为10的线程池.然后通过 executorService.execute( Runnable runnable) 的方式提交一个任务, 这样可以最大并行地执行10个任务. 如果需要并行的线程更多, 那么 Executors.newFixedThreadPool(threadCount) 的参数可以设置大一些.我要吐槽一下, 你应该是把 Runnable 接口和 Thread 类混淆了吧? 实现 Runnable 接口的类不代表它就是在一个新的线程中运行, 你必须显示地地将 Runnable 提交到新线程中执行, 例如 executorService.execute(runnable) 或 new Thread(runnable).start().

眼眸繁星

不能直接调用run方法,线程的执行要通过Thread.start方法。直接调用run方法和调用普通方法没有区别。new&nbsp;Thread(tLbData).start()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java