写好true和false变化的方法
private static volatile boolean flag= true;
public static void stopTask() {
flag = false;
}
public static void startTask() {
flag = true;
}
多次调用单个线程(定时任务模拟调用线程)
@Scheduled(cron = "*/1 * * * * ?")
public void testThread() throws Exception {
if (flag==true){
new Thread(()-> {
System.out.println("--------------------" );
}).start();
}}
单个线程内部循环(定时任务模拟调用线程(单个))
@Scheduled(cron = "0 0 * * * ?")
public void testThread1() throws InterruptedException {
//单线程循环使用此方法
final Object obj = new Object();
//obj配合synchronized 对应同个对象
Thread thread= new Thread(()-> {
//循环100次
for (int i = 0; i <100 ; i++) {
System.out.println("--------------------" +i);
try {
Thread.sleep(2000);
//false让线程等待
if(flag==false){
synchronized (obj){
obj.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
while (true){
Thread.sleep(2000);
//true线程唤醒
//Thread.currentThread().getState()当前线程状态
//Thread.State.WAITING线程等待状态
if(flag==true&&Objects.equals(thread.getState(), Thread.State.WAITING)){
synchronized (obj){
obj.notify();
}
}
}
}
调用改变flag的方法
@GetMapping("/start")
public String start(){
Timing.startTask();
return "启动成功";
}
@GetMapping("/stop")
public String stop(){
Timing.stopTask();
return "关闭成功";
}