通过线程限制程序执行时间过长

前不久在项目实施中遇到这样的问题:在主系统A中需要调用外部系统B中的一段程序,但由于外部系统B极不稳定,导致主系统A为了等待外部系统B的响应需要很长时间,严重影响了主系统的正常运行。为了限制等待外部系统响应的时间,规定等待超过10秒定义为超时,所以就写了这样一段程序,如下:

主进程:

public class MainThread extends Thread {

public void run() {

try {
while(true)
{
System.out.println("[INFO]Main thread is running!");
sleep(100000);
}
}
catch (InterruptedException e) {
//e.printStackTrace();
System.out.println("[WARN]Main thread is interupt!");
}

function();
}

public void function() {
System.out.println("[INFO]Function is in Action!");
}

public static void main(String[] args)
{
MainThread main = new MainThread();
main.start();
new TimedThread(main,10000).start();
}

}

主进程中定义执行主体,以及中断后的超时处理程序。

超时进程:

public class TimedThread extends Thread {

Thread mainThread;
long waitTime;

public TimedThread(Thread thread , long timed)
{
mainThread = thread;
waitTime = timed;
}

public void run()
{
try {
sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}

if(mainThread.isAlive())
{
System.out.println("[INFO]Main thread must be interrupted in a minute!");
mainThread.interrupt();
}
}

}



超时进程中定义等待超时时间后,中断主进程。

Main中实例化主进程和超时进程并同时启动。主进程启动后,超时进程休息10秒后发现主进程仍然在运行,便中断主进程并抛出中断异常,主进程处理完中断异常后继续完成后面程序后停止。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值