There can be multiple ways to
stop a thread after certain time period. I choose below approach.
Just interrupt the thread,
when thread reaches to specified time.
Step 1: Create TimerTask that interrupts the thread after
given time.
TimeoutTask.java
package com.sample.app;
import java.util.TimerTask;
public class TimeoutTask extends TimerTask {
Thread thread;
TimeoutTask(Thread thread) {
this.thread = thread;
}
public void run() {
if (thread != null && thread.isAlive()) {
thread.interrupt();
}
}
}
Step 2: Create runnable task that schedules the timer task
before starting execution.
MyTask.java
package com.sample.app;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
public class MyTask implements Runnable {
private long timeoutInSeconds;
Timer timer;
MyTask(long timeoutInSeconds) {
this.timeoutInSeconds = timeoutInSeconds;
timer = new Timer(true);
}
@Override
public void run() {
timer.schedule(new TimeoutTask(Thread.currentThread()), timeoutInSeconds * 1000);
int count = 0;
while (true) {
count++;
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("Executed for " + count + " seconds");
} catch (InterruptedException e) {
System.out.println("Task interrupted");
break;
}
}
}
}
App.java
package com.sample.app;
public class App {
public static void main(String args[]) {
// Set the time out for task
MyTask task = new MyTask(5);
Thread thread = new Thread(task);
thread.start();
}
}
Run App.java, you will see below
messages in console.
Executed for 1 seconds Executed for 2 seconds Executed for 3 seconds Executed for 4 seconds Task interrupted
You may
like
No comments:
Post a Comment