关于超时任务的实现



package test.thread;

import java.util.Timer;
import java.util.TimerTask;

public class MainThread {
private Object lock = new Object();

public void waitLock() throws InterruptedException {
synchronized (lock) {
lock.wait();
}
}

public void notifyLock() {
synchronized (lock) {
lock.notify();
}
}

/**
* @param args
* 关于超时任务的实现 实现功能:处理一批任务,如果某个任务的处理时间超过最大处理时间,则终止该任务的执行,继续执行下一个任务
* 实现思路:三线程实现,处理一个任务时,启动一个任务处理线程处理方案,再启动一个定时器线程检测是否超时,并通过一个同步变量保证任务时串行执行的。
* @throws InterruptedException
*/
public static void main(String[] args) {

MainThread mainThread = new MainThread();

for (int i = 2; i <= 20; i += 2) {
System.out.println("start task!" + i);
ProccessThread proccessThread = new ProccessThread(mainThread,i * 1000);
MonitorThread monitorThread = new MonitorThread(mainThread);
long maxProccessTime = 8 * 1000;// 每个任务的最大处理时间
Timer timer = new Timer();
timer.schedule(monitorThread, maxProccessTime);
proccessThread.start();
try {
mainThread.waitLock();
} catch (InterruptedException e) {
e.printStackTrace();
}
proccessThread.stop();
timer.cancel();
System.out.println("end task!" + i);
}
}

}

/**
* 定时器线程检测
* @author liuhui
*
*/
class MonitorThread extends TimerTask {
private MainThread mt;

public MonitorThread(MainThread mt) {
super();
this.mt = mt;
}

@Override
public void run() {
System.out.println("ThreadID:" + " MonitorThread running!");
mt.notifyLock();
}

}

/**
* 任务处理线程
* @author liuhui
*
*/
class ProccessThread implements Runnable {
private MainThread mt;
private Thread thread;
private long processTime;
public static int sec = 1;

public ProccessThread(MainThread mt, long processTime) {
super();
this.mt = mt;
this.processTime = processTime;
}

private void doSomething() {
try {
// do something
// thread.sleep(100*1000); //异常情况
// thread.sleep(1*1000); //正常情况
thread.sleep(processTime); // 正常情况
System.out.println("ThreadID:" + thread.getId() + ">>> Normal Process! processTime=" + processTime);

} catch (InterruptedException e) {
// e.printStackTrace();
System.out.println("ThreadID:" + thread.getId() + ">>> AbNormal Proccess! processTime=" + processTime);
}

}

public void run() {
System.out.println("ThreadID:" + thread.getId() + ">>> starting!");
doSomething();
mt.notifyLock();
System.out.println("ThreadID:" + thread.getId() + ">>> ending ok!");

}

public void start() {
thread = new Thread(this);
thread.start();

}

public void stop() {
thread.interrupt();// 如果任务在正常时间内不能退出,认为产生interrupt,强行地退出 (run方法正常结束)
thread.stop();
try {
Thread.sleep(sec * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadID:" + thread.getId() + ">>> stoping end!");
thread = null;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值