0

我第一次使用 wait 和 notify() 方法,我尝试过这种方式。

示例代码

public class Tester
{
static boolean closing == false;
static int n;
DateTime dt = new DateTime();
int getMin = dt.getMinuteOfDay(); //minute of the day
int tempMin = dt.getMinuteOfDay()+5;// minute of the day + 5 minutes

public static void setClosing(boolean b)
{
    closing = b;        
}

public static int getN()
{
    return n;
}

class notifier extends Thread 
{
    public void run()
    {
        synchronized(this)
        {
            while(getMin == tempMin || closing == true)
            {
                notify();
            }
        }
    }
}

public void starter() throws InterruptedException 
{        
    notifier nn = new notifier();
    while(n==1)
    {
        notify.start();
        if(closing == false)
        {
            synchronized(notify)
            {
                nn.wait();
                mailreader();
                getMin = getMin+5;
                tempMin = tempMin+5;
            }
        }
        else
        {
            n=2;
        }
    }
}
}

主班

public class Tester2 extends WindowAdapter
{
public Tester2()
{        
    frame = new JFrame();
    frame.addWindowListener(this);
    frame.setVisible(true);
    Tester t = new Tester();
    t.starter();
}

@Override
public void windowClosing(WindowEvent e)
{
    Tester.setClosing(true);
    while(Tester.getN() != 2)
    {
        //wait
    }
    frame.dispose();        
}

public static void main(String args[])
{
    Tester2 t = new Tester2();        
}    
}

我每 5 分钟调用一次 mailreader()方法来执行一些任务,但是

当用户关闭 Jframe 时,主类的 关闭设置为 true,我想退出通知程序类中的 while 循环。

我在这里要做的就是,当用户关闭 JFrame 时,我不希望 mailreader() 在中间停止并退出,而是希望 JFrame 等到方法完成然后关闭或者如果它正在等待模式(通知程序类)我想退出它并退出

4

1 回答 1

1

如果您只想在后台线程中定期运行某些东西,然后在应用程序关闭时以有序的方式取消,那么您不需要所有这些。相反,您可以创建一个 Runnable 循环、睡眠并进行邮件阅读,当中断时退出(Runnable 可以控制它何时处理中断,因此它不在中间)。启动线程后,让 GUI 保留对它的引用,以便它可以在关闭时对其调用中断。

这是一个如何使用中断取消线程的示例

于 2013-04-10T15:37:06.523 回答