public class TestTask extends TimerTask {
private Boolean error;
public TestTask(boolean error){
this.error=error;
}
@Override
public void run() {
System.out.println("runing task");
if (error) {
throw new RuntimeException();
}
}
}
package com.ljq.mydemo.thread.pool.timer;
import java.util.Timer;
public class TestMain {
private static Timer timer=new Timer();
public static void main(String[] args) throws InterruptedException {
TestTask task1=new TestTask(true);
System.out.println("start task1===========");
timer.schedule(task1,1);
Thread.sleep(5000);
TestTask task2=new TestTask(false);
timer.schedule(task2,1);
System.out.println("end task2===========");
}
}
package com.ljq.mydemo.thread.pool.timer;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class OptimizeTask {
public static volatile int i=1;
public static void main(String[] args) throws InterruptedException {
ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
scheduled.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("start ......"+i);
if(i%2==0){
throw new RuntimeException();
}
System.out.println("end ......"+i);
i++;
}
}, 0, 40, TimeUnit.MILLISECONDS);
Thread.sleep(5000);
scheduled.shutdown();
}
}
package com.ljq.mydemo.thread.pool.timer;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class OptimizeTask2 {
public static volatile int i=1;
public static void main(String[] args) throws InterruptedException {
ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
scheduled.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("start ......"+i);
if(i>3){
throw new RuntimeException();
}
System.out.println("end ......"+i);
i++;
}
}, 0, 50, TimeUnit.MILLISECONDS);
Thread.sleep(6000);
System.out.println(scheduled.isShutdown());
scheduled.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("start2 ......"+i);
if(i>6){
throw new RuntimeException();
}
System.out.println("end2 ......"+i);
i++;
}
}, 0, 50, TimeUnit.MILLISECONDS);
Thread.sleep(5000);
scheduled.shutdown();
}
}