I am using wait and notify() methods for first time and I tried in this way.
sample codes
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;
}
}
}
}
main class
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();
}
}
I am calling mailreader() method for every 5minutes to perform some task, but
when user closes the Jframe the closing is set to true from main class i want to come out of the while loop in notifier class.
All I am trying to do here is, when user closes the JFrame, i don't want the mailreader() to be stopped in middle and exit, instead i want the JFrame to wait until the method is finished and then close or if it is waiting mode(notifier class) i want to come to out of it and exit
If all you want to do is have something run periodically in a background thread, then get canceled in an orderly manner when the application closes, you don't need all this. Instead you can make a Runnable that loops, sleeping and doing its mail-reading, which quits when interrupted (the Runnable can control when it handles the interrupt so it's not in the middle of something). Once you start the thread, have the GUI keep a reference to it so it can call interrupt on it when closing.
Here's an example of how to cancel a thread using interrupt .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.