一个定时器(使用的Timer类) 遇到一些问题:
      写了一个定时器监听器,当启动服务器的时候,就启动了定时器; 
              问题是 :页面上有一个复选框,当选择的时候调用定时器,否则就停止调用, 怎么控制它??不知道该怎么去控制它.
     

解决方案 »

  1.   

    return 一个onchecked事件点选的话,timer暂停,空的话,timer继续
      

  2.   

    可以用复选框同步一个变量,在run方法中由这个变量控制是否执行任务。
    变量可以根据需求设为类属性、存储在Session或数据库、或其他方式。
      

  3.   

    package thread;import javax.swing.SwingUtilities;/**
     * This is the 3rd version of SwingWorker (also known as
     * SwingWorker 3), an abstract class that you subclass to
     * perform GUI-related work in a dedicated thread.  For
     * instructions on using this class, see:
     * 
     * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
     *
     * Note that the API changed slightly in the 3rd version:
     * You must now invoke start() on the SwingWorker after
     * creating it.
     */
    public abstract class SwingWorker {
        private Object value;  // see getValue(), setValue()
        private Thread thread;    /** 
         * Class to maintain reference to current worker thread
         * under separate synchronization control.
         */
        private static class ThreadVar {
            private Thread thread;
            ThreadVar(Thread t) { thread = t; }
            synchronized Thread get() { return thread; }
            synchronized void clear() { thread = null; }
        }    private ThreadVar threadVar;    /** 
         * Get the value produced by the worker thread, or null if it 
         * hasn't been constructed yet.
         */
        protected synchronized Object getValue() { 
            return value; 
        }    /** 
         * Set the value produced by worker thread 
         */
        private synchronized void setValue(Object x) { 
            value = x; 
        }    /** 
         * Compute the value to be returned by the <code>get</code> method. 
         */
        public abstract Object construct();    /**
         * Called on the event dispatching thread (not on the worker thread)
         * after the <code>construct</code> method has returned.
         */
        public void finished() {
        }    /**
         * A new method that interrupts the worker thread.  Call this method
         * to force the worker to stop what it's doing.
         */
        public void interrupt() {
            Thread t = threadVar.get();
            if (t != null) {
                t.interrupt();
            }
            threadVar.clear();
        }    /**
         * Return the value created by the <code>construct</code> method.  
         * Returns null if either the constructing thread or the current
         * thread was interrupted before a value was produced.
         * 
         * @return the value created by the <code>construct</code> method
         */
        public Object get() {
            while (true) {  
                Thread t = threadVar.get();
                if (t == null) {
                    return getValue();
                }
                try {
                    t.join();
                }
                catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // propagate
                    return null;
                }
            }
        }
        /**
         * Start a thread that will call the <code>construct</code> method
         * and then exit.
         */
        public SwingWorker() {
            final Runnable doFinished = new Runnable() {
               public void run() { finished(); }
            };        Runnable doConstruct = new Runnable() { 
                public void run() {
                    try {
                        setValue(construct());
                    }
                    finally {
                        threadVar.clear();
                    }                SwingUtilities.invokeLater(doFinished);
                }
            };        Thread t = new Thread(doConstruct);
            threadVar = new ThreadVar(t);
        }    /**
         * Start the worker thread.
         */
        public void start() {
            Thread t = threadVar.get();
            if (t != null) {
                t.start();
            }
        }
    }
      

  4.   

    package thread;import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;class Example1 extends JPanel {
        JProgressBar progressBar = new JProgressBar();
        static int NUMLOOPS = 100;
        JLabel statusField = new JLabel("Click Start to begin", JLabel.CENTER);
        SwingWorker worker;
        JButton startButton;
        JButton interruptButton;
        Border spaceBelow = BorderFactory.createEmptyBorder(0, 0, 5, 0);    JButton getStartButton() {
            return startButton;
        }    /**
         * When the worker needs to update the GUI we do so by queuing
         * a Runnable for the event dispatching thread with 
         * SwingUtilities.invokeLater().  In this case we're just
         * changing the progress bars value.
         */
        void updateStatus(final int i) {
            Runnable doSetProgressBarValue = new Runnable() {
                public void run() {
                    progressBar.setValue(i);
                }
            };
            SwingUtilities.invokeLater(doSetProgressBarValue);
        }    
        /**
         * This method represents the application code that we'd like to 
         * run on a separate thread.  It simulates slowly computing 
         * a value, in this case just a string 'All Done'.  It updates the 
         * progress bar every half second to remind the user that
         * we're still busy.
         */
        Object doWork() {
            try {
                for(int i = 0; i < NUMLOOPS; i++) {
                    updateStatus(i);
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    Thread.sleep(500);
                }
            }
            catch (InterruptedException e) {
                updateStatus(0);
                return "Interrupted";  // SwingWorker.get() returns this
            }
            return "All Done";         // or this
        }
        /**
         * This action listener, called by the "Start" button, effectively 
         * forks the thread that does the work.
         */
        ActionListener startListener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                startButton.setEnabled(false);
                interruptButton.setEnabled(true);
                statusField.setText("Working...");            /* Invoking start() on the SwingWorker causes a new Thread
                 * to be created that will call construct(), and then
                 * finished().  Note that finished() is called even if
                 * the worker is interrupted because we catch the
                 * InterruptedException in doWork().
                 */
                worker = new SwingWorker() {
                    public Object construct() {
                        return doWork();
                    }
                    public void finished() {
                        startButton.setEnabled(true);
                        interruptButton.setEnabled(false);
                        statusField.setText(get().toString());
                    }
                };
                worker.start();
            }
        };
        /**
         * This action listener, called by the "Cancel" button, interrupts
         * the worker thread which is running this.doWork().  Note that
         * the doWork() method handles InterruptedExceptions cleanly.
         */
        ActionListener interruptListener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                interruptButton.setEnabled(false);
                worker.interrupt();
                startButton.setEnabled(true);
            }
        };    /** 
         * And now for a little assembly.  Put together the buttons, progress 
         * bar and status text field.  
         */
        Example1(String name) {
            setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black),name));        progressBar.setMaximum(NUMLOOPS);        startButton = new JButton("Start");
            startButton.addActionListener(startListener);
            startButton.setEnabled(true);        interruptButton = new JButton("Cancel");
            interruptButton.addActionListener(interruptListener);
            interruptButton.setEnabled(false);        JComponent buttonBox = new JPanel();
            buttonBox.add(startButton);
            buttonBox.add(interruptButton);        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
            add(buttonBox);
            add(progressBar);
            add(statusField);
            statusField.setAlignmentX(CENTER_ALIGNMENT);        buttonBox.setBorder(spaceBelow);
            Border pbBorder = progressBar.getBorder();
            progressBar.setBorder(BorderFactory.createCompoundBorder(
                                            spaceBelow,
                                            pbBorder));
        }    Example1() {
            this("Example 1");
        }
    }
      

  5.   

    package thread;//import com.sun.java.swing.*;  //old package name
    import javax.swing.*;  class Example2 extends Example1 {    Example2() {
            super("Example 2");
        }    /**
         * Popup a modal confirm dialog and block until the user responds.
         * Return true unless the user selects "NO".
         */
        boolean waitForUserConfirmation() throws InterruptedException {        /* We're going to show the modal dialog on the event dispatching
             * thread with SwingUtilities.invokeLater(), so we create a 
             * Runnable class that shows the dialog and stores the user's
             * response.
             */
            class DoShowDialog implements Runnable {
                boolean proceedConfirmed;
                public void run() {
                    Object[] options = {"Continue", "Cancel"};
                    int n = JOptionPane.showOptionDialog(Example2.this, 
                                                "Example2: Continue?",
                                                "Example2",
                                                JOptionPane.YES_NO_OPTION,
                                                JOptionPane.QUESTION_MESSAGE,
                                                null,
                                                options,
                                                "Continue");
                    proceedConfirmed = (n == JOptionPane.YES_OPTION);
                }
            }
            DoShowDialog doShowDialog = new DoShowDialog();        /* The invokeAndWait utility can throw an InterruptedException,
             * which we don't bother with, and an InvocationException.
             * The latter occurs if our Runnable throws - which would indicate
             * a bug in DoShowDialog.  The invokeAndWait() call will not return 
             * until the user has dismissed the modal confirm dialog.
             */
            try {
                SwingUtilities.invokeAndWait(doShowDialog);
            }
            catch (java.lang.reflect.InvocationTargetException e) {
                e.printStackTrace();
            }
            return doShowDialog.proceedConfirmed;
        }
        public void getMyTread(){
         SwingUtilities.invokeLater(new Runnable(){ @Override
    public void run() {
    // TODO Auto-generated method stub

    }
        
         });
        }
        /**
         * This is just a copy of Example1.doWork() with one extra wrinkle.
         * After about two seconds we ask the user to confirm with
         * a modal dialog (see waitForUserConfirmation()); if the answer
         * is NO then we short circuit.
         */
        Object doWork() {
            try {
                for(int i = 0; i < NUMLOOPS; i++) {
                    updateStatus(i);
                    if (i == 4) {
                        if (!waitForUserConfirmation()) {
                            updateStatus(0);
                            return "Not Confirmed";
                        }
                    }
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    Thread.sleep(500);
                }
            }
            catch (InterruptedException e) {
                updateStatus(0);
                return "Interrupted";  // SwingWorker.get() returns this
            }
            return "All Done";         // or this
        }
    }
      

  6.   

    我用 的spring ,我的业务在下面的方法中写的,
    public class  A{
    protected ModelAndView handle(HttpServletRequest request,
    HttpServletResponse response, Object command, BindException arg3)
    throws Exception {
         if("update".equals("operate")){
           int flag;//这个就是复选框 选种与否的标记;(该标记也在数据库里面存着)
                 if(flag==0){
                            .........
                          return ModelAndView("a.jsp");
                  }else{
                             ..........
                        return ModelAndView("b.jsp");         
                }
        }}
    }
     页面提交是这样的
     var forma = document.getElementById("form1");     
        forma.action="A.do?operateType=update&flag="+flag;还有个问题是我的定时器 run(){ }
    中怎么能把上面写到的业务部分加进去?
      

  7.   

    package thread;import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    //import com.sun.java.swing.*;  //old package name
    import javax.swing.*;           //new package namepublic class ThreadsExample {    /**
         * This is strictly boilerplate: set the look and feel, configure the
         * frame, pack(), show().
         */
        public static void main(String[] args) {
            String laf = UIManager.getCrossPlatformLookAndFeelClassName();
            try {
                UIManager.setLookAndFeel(laf);
            }
            catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
            JFrame f = new JFrame("Worker Thread Examples");
            WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {System.exit(0);}
            };
            f.addWindowListener(l);         Container contentPane = f.getContentPane();
            final Example1 ex1 = new Example1();
            contentPane.setLayout(new GridLayout(1, 0));
            contentPane.add(ex1);
            contentPane.add(new Example2());
            f.pack();
            f.show();
    //        ex1.getStartButton().requestFocus();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    ex1.getStartButton().requestFocus();  //XXX: can't do this until now
                }
            });
        }
    }
      

  8.   

    1 你的定时器无论是一个servlet 还是 servlet调用的一个类,里面增加一个static的方法class MyTimer {
      public static void setStatus(boolean run){
        ... // 根据 run ,确定你的timer是否运行,至于怎么启动和终止,你自己解决
      }
      ...
    }2 在页面,当点击复选框是,调用后台的一个程序,让他直接调用那个 static 方法,比如 boolean run = .../
     MyTimer.setStatus(run);// 这样就可以了!
      至于怎么掉用? 可以表单提交,也可以用Ajax 提交!
      

  9.   

    Java codeclass MyTimer {
      public static void setStatus(boolean run){
        ... // 根据 run ,确定你的timer是否运行,至于怎么启动和终止,你自己解决
      }
      ...
    }=======================前台可以用JS  onclick或者onchangse 事件来写``