JAVA:如果函数持续超过1秒,如何中断函数
我的程序中有这样的代码JAVA:如果函数持续超过1秒,如何中断函数,java,time,interrupt,Java,Time,Interrupt,我的程序中有这样的代码 for(int i = 0; i < 100000; i++) { func(i); } for(int i=0;i
for(int i = 0; i < 100000; i++) {
func(i);
}
for(int i=0;i<100000;i++){
func(i);
}
对于i的大多数值,func的持续时间不到1秒,但对于某些值,它可能持续几分钟,因此如果持续时间太长,我需要中断它
如何才能做到这一点?中断一个可能花费太长时间的函数的一种方法是在单独的线程中运行它。然后,您可以在一秒钟后向该线程发送一条消息,告诉它停止。在不使用线程的情况下,您可以通过以下代码替换func来处理它:
function process(int i, long maxMiliseconds) {
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - start < maxMiliseconds) {
//do your processing one step at a time
// return an answer if you have one.
}
//make some record of the fact that the process timed out for i.
return;
}
函数进程(整数i,长最大毫秒){
长启动=System.currentTimeMillis();
while(System.currentTimeMillis()-开始<最大毫秒){
//一次只处理一个步骤
//如果有答案,请返回答案。
}
//记录进程为i超时的事实。
返回;
}
中断可能花费太长时间的函数的一种方法是在单独的线程中运行它。然后,您可以在一秒钟后向该线程发送一条消息,告诉它停止。在不使用线程的情况下,您可以通过以下代码替换func来处理它:
function process(int i, long maxMiliseconds) {
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - start < maxMiliseconds) {
//do your processing one step at a time
// return an answer if you have one.
}
//make some record of the fact that the process timed out for i.
return;
}
函数进程(整数i,长最大毫秒){
长启动=System.currentTimeMillis();
while(System.currentTimeMillis()-开始<最大毫秒){
//一次只处理一个步骤
//如果有答案,请返回答案。
}
//记录进程为i超时的事实。
返回;
}
您可以在单独的线程中启动func(),然后在线程上执行方法join(long millis)
以等待1秒,直到结束。但线程仍将运行,直到完成(stop()
method已弃用)。方法是在当前线程中获得控制权并做出适当的反应。您可以在单独的线程中启动func(),然后在线程上执行方法join(long millis)
,等待1秒,直到结束。但线程仍将运行,直到完成(stop()
method已弃用)。这样做的方法是在当前线程中获得控制权,并做出适当的反应我就是这么看的。我确信有一些方法可以用更少的代码行来完成,但这是一个简单的解决方案
如果您想运行func(i)代码>在线程中
那么这将是另一个故事
public class MainClass {
private static boolean riding, updated = false;
private static int timeout = 10000;
public static void main(String[] args) {
while (true) {
if (!riding){
long endTimeMillis = System.currentTimeMillis() + timeout;
func(endTimeMillis);
}
}
}
private static void func(long endTimeMillis) {
for (int i = 0; i < 9999; i++) {
if ((!riding && System.currentTimeMillis() < endTimeMillis) || updated) {
updated = false;
System.out.println("run method main function");
riding = true;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " > "
+ endTimeMillis);
if (System.currentTimeMillis() > endTimeMillis) {
updated = true;
System.out.println("overdue");
riding = false;
break;
}
}
}
riding = false;
}
}
public类MainClass{
私有静态布尔乘骑,更新=false;
私有静态int超时=10000;
公共静态void main(字符串[]args){
while(true){
如果(!骑马){
long-endTimeMillis=System.currentTimeMillis()+超时;
func(endTimeMillis);
}
}
}
专用静态无效函数(long-endTimeMillis){
对于(int i=0;i<9999;i++){
if((!riding&System.currentTimeMillis()”
+endTimeMillis);
if(System.currentTimeMillis()>endTimeMillis){
更新=真;
系统输出打印项次(“过期”);
骑马=假;
打破
}
}
}
骑马=假;
}
}
我就是这么看的。我确信有一些方法可以用更少的代码行来完成,但这是一个简单的解决方案
如果您想运行func(i)代码>在线程中
那么这将是另一个故事
public class MainClass {
private static boolean riding, updated = false;
private static int timeout = 10000;
public static void main(String[] args) {
while (true) {
if (!riding){
long endTimeMillis = System.currentTimeMillis() + timeout;
func(endTimeMillis);
}
}
}
private static void func(long endTimeMillis) {
for (int i = 0; i < 9999; i++) {
if ((!riding && System.currentTimeMillis() < endTimeMillis) || updated) {
updated = false;
System.out.println("run method main function");
riding = true;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " > "
+ endTimeMillis);
if (System.currentTimeMillis() > endTimeMillis) {
updated = true;
System.out.println("overdue");
riding = false;
break;
}
}
}
riding = false;
}
}
public类MainClass{
私有静态布尔乘骑,更新=false;
私有静态int超时=10000;
公共静态void main(字符串[]args){
while(true){
如果(!骑马){
long-endTimeMillis=System.currentTimeMillis()+超时;
func(endTimeMillis);
}
}
}
专用静态无效函数(long-endTimeMillis){
对于(int i=0;i<9999;i++){
if((!riding&System.currentTimeMillis()”
+endTimeMillis);
if(System.currentTimeMillis()>endTimeMillis){
更新=真;
系统输出打印项次(“过期”);
骑马=假;
打破
}
}
}
骑马=假;
}
}
如果不需要其他线程,可以将异常处理注入func。
public static void main(String[] args)
{
try
{
func(1);
}
catch (timeR e)
{
System.out.println("enough!")
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void func(int a) throws timeR //your func needs to throw something when time-is-up
{
long time1,time2; //reference time and current time
time1=System.nanoTime(); //having reference
time2=System.nanoTime(); //init of current
while(true) //You did not put your func, so I used inf-while
{
//here whatever your func does,
//.....
//.....
//below line checks if time is up
time2=System.nanoTime();
if((time2-time1)>1000000000) //1000000000 is 1 second or 1Billion nanoseconds
{ throw new timeR("time is up!");}
//this is throwing(an alternative exit from this function)
}
}
static class timeR extends Exception
{
//Parameterless Constructor
public timeR()
{
}
//Constructor that accepts a message
public timeR(String message)
{
super(message);
}
}
输出:调用func()后1秒:
也许你不想看到红色消息,那么只需注释掉e.printStackTrace()。
玩得开心。如果不需要其他线程,可以将异常处理注入func中。
public static void main(String[] args)
{
try
{
func(1);
}
catch (timeR e)
{
System.out.println("enough!")
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void func(int a) throws timeR //your func needs to throw something when time-is-up
{
long time1,time2; //reference time and current time
time1=System.nanoTime(); //having reference
time2=System.nanoTime(); //init of current
while(true) //You did not put your func, so I used inf-while
{
//here whatever your func does,
//.....
//.....
//below line checks if time is up
time2=System.nanoTime();
if((time2-time1)>1000000000) //1000000000 is 1 second or 1Billion nanoseconds
{ throw new timeR("time is up!");}
//this is throwing(an alternative exit from this function)
}
}
static class timeR extends Exception
{
//Parameterless Constructor
public timeR()
{
}
//Constructor that accepts a message
public timeR(String message)
{
super(message);
}
}
输出:调用func()后1秒:
也许你不想看到红色消息,那么只需注释掉e.printStackTrace()。
玩得开心。FutureTask非常适合超时执行代码
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {
/* Do here what you need */
return null; /* Or any instance */
}
}) {
};
try {
Object result = task.get(1, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimeoutException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
}
FutureTask非常适合超时执行代码
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {
/* Do here what you need */
return null; /* Or any instance */
}
}) {
};
try {
Object result = task.get(1, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimeoutException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
}
func(inti)
做什么?您可以通过此SNIP限制总体执行时间