等待并通知条件Java

时间:2013-04-10 10:19:36

标签: 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 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等到方法完成然后关闭或者如果它是等待模式(通知程序类)我想要退出并退出

1 个答案:

答案 0 :(得分:1)

如果您想要做的就是在后台线程中定期运行某些内容,那么在应用程序关闭时以有序的方式取消,您不需要所有这些。相反,你可以创建一个循环,休眠和执行邮件读取的Runnable,它在中断时退出(Runnable可以控制它何时处理中断,因此它不在某些东西的中间)。一旦你启动线程,让GUI保持对它的引用,这样它就可以在关闭时调用它。

这是an example of how to cancel a thread using interrupt

相关问题