2013-04-10 96 views
0

我第一次使用wait和notify()方法,我尝试了这种方式。等待,并通知条件Java

示例代码

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分钟执行一些任务,但

当用户关闭的JFrame的

正在关闭设置为从主类真正我想出来的while循环中通知人类。

我想在这里做的是,当用户关闭JFrame时,我不想让mailreader()在中间停止并退出,而是我希望JFrame等到方法结束后再执行关闭或如果它是等待模式(通知类),我想出来它并退出

回答

1

如果你想要做的是有东西定期运行在后台线程,然后取消有序的方式,当应用程序关闭,你不需要这一切。相反,您可以创建一个Runnable,它可以循环,休眠和进行邮件阅读,当它中断时退出(Runnable可以控制何时处理中断,因此它不在中间)。一旦你开始线程,让GUI保持一个引用,以便它可以在关闭时调用中断。

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