Reputation: 557
How can I call different methods in the same loop with delay?
time 0: call A
+100ms: call B
+100ms: call C
+100ms: call D
...
+100ms: call X
stopLoop()
I tried:
Thread thread = new Thread() {
@Override
public void run() {
try {
while (true) {
call A();
sleep(100);
call B();
sleep(100);
call C();
sleep(100);
call D();
sleep(100);
call E();
sleep(100);
thread.stop(); ???
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
It is working except the stop(), plus it doesn't look logical to kill a thread from inside the same thread.
Upvotes: 1
Views: 220
Reputation: 12843
Thread.interrupt() is a perfectly acceptable way of doing this.
Interrupts this thread. Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.
Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?
Try something like this:
while (!Thread.currentThread().isInterrupted()) {
//Call methods .
Thread.currentThread().interrupt();
}
Upvotes: 2