创建多个线程处理数据库中多条数据

处理思路:(1)比如查出100万数据(2):创建10个线程,循环处理这些数据,每一次处理调用一个线程,如果某一个线程被占用了,那么就调用另外一个线程,以此类推,这样就不需要等待上一个线程的完毕,从而加快处理的速度。

//需要引用的线程类:这个是jdk1.8自带的线程处理jia包
import java.util.concurrent.ExecutorService;
@Controller
@RequestMapping("/hznzw")
public class HznzwProductAction {

	@RequestMapping("/product/initProductDetail.html")
		public String initProductDetail(@RequestParam(value="s1",required=true)Integer s1,
			@RequestParam(value="s2",required=true)Integer s2){
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("start", s1);
			map.put("end", s2);
			//根据数据里表里面的id查询出需要处理的数据
			List<HznzwProduct> hznzwProducts = hznzwProductService.queryProductList(map);
	         //创建10个线程
			ExecutorService executor = Executors.newFixedThreadPool(10);
			//调用线程处理数据
			for (HznzwProduct hznzwProduct : hznzwProducts) {
				executor.execute(new ToServer(hznzwProduct .getHznzwProId().toString(),product));
			}
			//关闭线程池
			executor.shutdown();
	
			return "";
		}
		public class ToServer implements Runnable{
	
			private String proId;

		private MallProduct product;

		public ToServer(String proId,MallProduct product) {
			this.proId = proId;
			this.product = product;
		}
		@Override
		public void run() {
			getHznzwProduct(proId,product);
		}
		}
		private void getHznzwProduct(String proId,MallProduct product){
			//业务处理
			//比如插入或者修改数据。。
			ProductGet gg	= null;
		try {
			gg = getHznzwState(proId,URL);
			if(gg.getData() != null && gg.getData().getProductDtc() != null){
				product.setDtc7dayHours(gg.getData().getProductDtc().getDTC7Day_Hours());
				product.setDtc15dayHours(gg.getData().getProductDtc().getDTC15Day_Hours());
			}else{
				product.setDtc7dayHours(1000);
				product.setDtc15dayHours(1000);
			}
			product.setUpdateTime(new Date());
			//修改子表与主表价格
			mallProductService.updateByPrimaryKeySelective(product);
		} catch (Exception e) {
			e.printStackTrace();
		}
		}
	}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您好!对于查询数据库百万条数据的情况,使用多线程数据库分页查询是一种常见的优化策略。下面是一个基本的实现思路: 1. 多线程处理:将数据查询任务分配给多个线程并行执行,提高查询效率。可以使用Java的线程池来管理线程,例如使用`ExecutorService`和`Callable`接口。 2. 数据库分页查询:通过分页查询的方式减少单次查询的数据量,避免一次性查询大量数据导致性能问题。可以使用SQL语句的`LIMIT`子句来实现分页查询,例如`SELECT * FROM table_name LIMIT offset, limit`,其`offset`表示偏移量,`limit`表示每页查询的数据量。 下面是一个简单的示例代码: ```java import java.sql.*; import java.util.concurrent.*; public class DatabaseQuery { private static final int PAGE_SIZE = 100; // 每页查询的数据量 public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(10); // 创建线程池 Connection connection = null; try { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password"); int totalRows = getTotalRows(connection); // 获取数据总行数 int totalPages = (int) Math.ceil((double) totalRows / PAGE_SIZE); // 计算总页数 for (int page = 0; page < totalPages; page++) { int offset = page * PAGE_SIZE; threadPool.submit(new QueryTask(connection, offset)); } } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } threadPool.shutdown(); } } private static int getTotalRows(Connection connection) throws SQLException { try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM table_name")) { resultSet.next(); return resultSet.getInt(1); } } private static class QueryTask implements Callable<Void> { private Connection connection; private int offset; public QueryTask(Connection connection, int offset) { this.connection = connection; this.offset = offset; } @Override public Void call() throws Exception { try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM table_name LIMIT ?, ?")) { statement.setInt(1, offset); statement.setInt(2, PAGE_SIZE); ResultSet resultSet = statement.executeQuery(); // 处理查询结果 while (resultSet.next()) { // 处理每条数据 // ... } resultSet.close(); } return null; } } } ``` 以上示例代码仅供参考,具体的实现需要根据实际情况进行调整和优化。同时,请确保在使用多线程数据库查询时遵循相关的线程安全和数据库事务处理的规范。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值