我第一次使用 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 等到方法完成然后关闭或者如果它正在等待模式(通知程序类)我想退出它并退出