根据线程名停止线程工具类
public class ThreadUtils {
public static boolean killThreadByName(String name) {
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
System.out.println("现有线程数" + noThreads);
for (int i = 0; i < noThreads; i++) {
String nm = lstThreads[i].getName();
System.out.println("线程号:" + i + " = " + nm);
if (nm.equals(name)) {
lstThreads[i].stop();
return true;
}
}
return false;
}
}
接口
public interface TestService {
void save();
}
实现类
@Service
public class TestServiceImpl implements TestService {
@Autowired
private ZhenggaiInfoTblMapper zhenggaiInfoTblMapper;
@Override
@Transactional(rollbackFor=RuntimeException.class)
public void save() {
for (int i = 0; i < 100000; i++) {
ZhenggaiInfoTbl zhenggaiInfoTbl = new ZhenggaiInfoTbl();
zhenggaiInfoTbl.setRowguid(CommUtils.getUUID());
zhenggaiInfoTbl.setZgjcguid("测试");
zhenggaiInfoTbl.setIssubmit("测试");
zhenggaiInfoTbl.setZgfktime(new Date());
zhenggaiInfoTbl.setZgfkunit("测试");
zhenggaiInfoTblMapper.insert(zhenggaiInfoTbl);
System.out.println("插入:"+i);
/*if(i==20000){
System.out.println(1/0);
}*/
}
}
}
控制器
@RestController
public class TestController {
@Autowired
private TestService testService;
@GetMapping("testThread")
public void test(String name) {
Thread thread = new Thread(() -> {
testService.save();
});
thread.setName(name);
thread.start();
}
@GetMapping("testStop")
public void testStop(String name) {
ThreadUtils .killThreadByName(name);
}
}
在调用接口时传一个随机参数就是线程名
在线程正在运行时,调用停止线程接口传入之前的线程名(也就是取消操作)
此时接口报错数据就会回滚了