等待并通知条件Java

等待并通知条件Java,java,multithreading,thread-safety,Java,Multithreading,Thread Safety,我第一次使用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

我第一次使用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等待方法完成后再关闭,或者如果它处于等待模式(notifier类)我想退出并退出

如果您只想在后台线程中定期运行某个程序,然后在应用程序关闭时以有序的方式取消,您不需要所有这些。相反,你可以做一个可运行的循环,睡觉和做邮件阅读,中断时退出(Runnabl可以控制当它处理中断,所以它不在某物的中间)。启动线程后,让GUI保留对它的引用,以便在关闭线程时调用中断

给你