示例代码实现创建多个线程异步打印表中不同行数据
1.主程序,线程启动类代码和线程代码
public class Mythread {
public void test() {
// 创建一个固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(10);
// 执行任务
for (int i = 3358; i < 3410; i++) {
executor.submit(new TestTask(bigDataService, (long) i));
}
// 关闭线程池
executor.shutdown();
}
}
@Slf4j
class TestTask implements Runnable {
private MyService myService;
private Long id;
public TestTask(MyService myService, Long id) {
this.myService= myService;
this.id = id;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
log.info("当前线程名称:{}", threadName);
myService.test(id);
}
}
2.接口及实现类代码
@Service
public interface MyService {
void test(Long id);
}
@Slf4j
@Service
public class MyServiceImpl implements MyService {
@Autowired
MyMapper myMapper;
public void test(Long id) {
MusemsMediaInformation mediaInformation = myMapper.selectTest(id);
if (mediaInformation == null) {
log.info("当前媒资id:{}不存在", id);
} else {
log.info("当前媒资id:{},name:{}", mediaInformation.getId(), mediaInformation.getName());
}
}
}
3.mapper代码
public interface MyMapper {
@Select("select * from musems_media_information where id = #{id}")
MusemsMediaInformation selectTest(@Param("id") Long id);
}