使等待线程跳过等待/继续的其余部分



我有一个场景,其中有一个线程在等待和执行任务之间循环。但是,我想中断对线程的等待(如果愿意的话,跳过其余的等待),继续执行任务。

有人知道怎么做吗?

我认为您需要的是实现wait()/notify()!查看本教程:http://www.java-samples.com/showtutorial.php?tutorialid=306

他们很多!如果您需要更具体的案例,请发布一些代码!

欢呼

您可以使用wait()notify()。如果您的线程正在等待,则需要通过从其他线程调用notify()来恢复它。

这就是Thread.interrupt的用途:

import java.util.Date;

public class Test {
    public static void main(String [] args) {
        Thread t1 = new Thread(){
            public void run(){
                System.out.println(new Date());
                try {
                    Thread.sleep(10000); // sleep for 10 seconds.
                } catch (InterruptedException e) {
                    System.out.println("Sleep interrupted");
                }
                System.out.println(new Date());
            }
        };
        t1.start();
        try {
            Thread.sleep(2000); // sleep for 2 seconds.
        } catch (InterruptedException e) {
            e.printStackTrace();  
        }
        t1.interrupt();
    }
}

线程t1将只休眠2秒,因为主线程会中断它。请记住,这将中断许多阻塞操作,如IO。

最新更新