关于阻塞线程
你好!程序设置的定时器为2s输出字符。有一个while循环,期中还设定了一个提示框,yes退出程序,no继续输出字符。可是为什么执行的时候,每按一次no,就会加速一秒输出???由于对线程的调用不是很了解,求高手指点指点。
下面是运行的代码:
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class TestTimer {
	
	public static void main(String[] args) {
		
		
		while(true){
			TimerPrinter listen = new TimerPrinter();
			Timer t = new Timer(2000, listen);
			t.start();
		
			int c =JOptionPane.showConfirmDialog(null, "Quit program?", "提示",JOptionPane.YES_NO_OPTION);
			if(c == JOptionPane.YES_NO_OPTION){
			
			System.exit(0);
			
			}
			
		}
		
	}
}
class TimerPrinter implements ActionListener{
	@Override
	public void actionPerformed(ActionEvent e) {
		Date now  = new Date();
		System.out.println("At the tone, the time is " + now);
		Toolkit.getDefaultToolkit().beep();
		
	}
	
}
              
                  java线程
                  timer
              
------解决方案--------------------你把定时器的定义和启动拿到循环外面去
------解决方案--------------------
正解!
        while(true){
            int c =JOptionPane.showConfirmDialog(null, "Quit program?", "提示",JOptionPane.YES_NO_OPTION);
            if(c == JOptionPane.YES_NO_OPTION){
                System.exit(0);
            }
        }
------解决方案--------------------
很明显你的理解是正确的。不过你的例子里面没有关于阻塞的东西