내 프로그램 난 대부분의 값JAVA : 그것은 이상 1 초
for(int i = 0; i < 100000; i++) {
func(i);
}
에 같은 코드를 가지고, FUNC 미만 1 초를 지속 마지막으로,하지만 일부 값이 지속될 수있는 경우 기능을 방해하는 방법 몇 분 간 지속되므로 너무 오래 지속되면 중단해야합니다.
어떻게하면됩니까?
내 프로그램 난 대부분의 값JAVA : 그것은 이상 1 초
for(int i = 0; i < 100000; i++) {
func(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;
}
다음이 결말에 대해 1 초 기다리는 스레드에 방법 join(long millis)
을 수행 스레드를 사용하지 않고, 아래의 코드로 FUNC를 교체하여 처리 할 수 있습니다. 그러나 스레드는 끝날 때까지 계속 실행됩니다 (stop()
메소드는 사용되지 않습니다). 이 방법은 현재 스레드에서 제어권을 얻고 적절하게 반응하는 것입니다.
이것이 내가 보는 방법입니다. 더 적은 코드 행에서이 방법을 사용하는 것이 확실하지만이 방법은 간단합니다.
func(i);
을 Thread
으로 실행하려면 다른 이야기가됩니다.
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;
}
}
다른 스레드를 원하지 않으면 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 후 일초() :
enough!
proje.lineerCebir$timeR: time is up!
at proje.lineerCebir.func(lineerCebir.java:198)
at proje.lineerCebir.main(lineerCebir.java:179)
은 어쩌면 당신은 빨간색 메시지를보고 싶지 않는, 그럼 그냥 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);
}
}
'func (int i)'의 기능은 무엇입니까? 이 스 니펫 (전체) 실행 시간을 제한 할 수는 있지만 특정 func (i) 호출 내에서 너무 많은 시간이 소비되는 경우 개별 호출을 제한하고 다음 호출을 계속 수행하려는 것처럼 들릴 수 있습니다. –
func (i)에서 아무 것도 할 수 없습니다. 입력을 기반으로 숫자의 의사 랜덤 시퀀스를 생성합니다. 거기에 또 다른 방법이 있을까요? – user2282875
func 메서드 표시 – stinepike