使用SPRING中的线程池ThreadPoolTaskExecutor实现JAVA并发
ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();poolTaskExecutor.setQueueCapacity(10000);poolTaskExecutor.setCorePoolSize(5);poolTaskExecutor.setMaxPoolSize(10);poolTaskExecutor.setKeepAliveSeconds(5000);poolTaskExecutor.initialize();
?
2,在线程池中执行某个线程
poolTaskExecutor.execute(new Thread(Objct...){...});?
二:需要返回值的情况
1,初始化线程池poolTaskExecutor,同上
?
2,新建一个类,实现Callable接口
class GetFromDB implements Callable<User> { private UserDao userDao; private Long userId; public GetFromDB(UserDao userDao, Long userId) { this.userDao = userDao; this.userId = userId; } public User call() throws DaoException { User user = userDao.getUserById(userId); return user; }}?
3,用之前的GetFromDB类构造一个FutureTask类
FutureTask<User> dbtask = new FutureTask<User>(GetFromDB);?
4,提交并执行
threadpool.submit(dbtask);?
5,得到返回值
try { User user = dbtask.get();} catch (Exception e) { if (e instanceof ExecutionException && ((ExecutionException) e).getCause() instanceof DaoException) { throw (DaoException) ((ExecutionException) e).getCause(); } else { 其他处理方式 }}?
注:一旦调用了get()方法,如果线程还未产生返回值,则将阻塞get()方法,直到得到返回值。基于此,如果你想确保线程执行完后才执行下一步操作,即使你不想得到返回值也可以调用一下此方法。当然这与多线程的初衷不符。
?
?
?
?