1

如何在同一个循环中延迟调用不同的方法?

time 0: call A  
+100ms: call B  
+100ms: call C  
+100ms: call D  
...  
+100ms: call X  
stopLoop()  

我试过:

    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();

除了 stop() 之外它正在工作,而且从同一个线程内部杀死一个线程看起来不合逻辑。

4

1 回答 1

2

Thread.interrupt() 是一种完全可以接受的方式。

线程#interrupt()

中断这个线程。除非当前线程正在中断自己,这总是允许的,否则会调用该线程的 checkAccess 方法,这可能会导致抛出 SecurityException。

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();
}
于 2013-03-30T15:34:23.487 回答