How to keep a method running continuously in background until the program ends?

后端 未结 2 534
Happy的楠姐
Happy的楠姐 2021-01-03 14:21

I want to know, how to keep a method running in the background. ie. this method starts when the program starts and keeps executing its statements until the program is closed

2条回答
  •  执笔经年
    2021-01-03 14:57

    In the simplest way, you could have something like this:

    import javax.swing.JFrame;
    
    public class TestBackgroudMethod {
    
        public static void main(final String[] args) {
    
            MyBackgroudMethod thread = new MyBackgroudMethod();
            thread.setDaemon(true);
            thread.start();
    
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JFrame jFrame = new JFrame();
                    jFrame.setSize(200, 200);
                    jFrame.setVisible(true);
                }
            });
        }
    
        public static class MyBackgroudMethod extends Thread {
    
            @Override
            public void run() {
                while (true) {
                    System.out.println("Executed!");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    
    }
    

    Edit


    Added sample with swing worker:

    import javax.swing.JFrame;
    import javax.swing.SwingWorker;
    
    public class TestBackgroudMethod {
    
        public static void main(final String[] args) {
    
            new SwingBackgroupWorker().execute();
    
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JFrame jFrame = new JFrame();
                    jFrame.setSize(200, 200);
                    jFrame.setVisible(true);
                }
            });
        }
    
        public static class SwingBackgroupWorker extends SwingWorker {
    
            @Override
            protected Object doInBackground() throws Exception {
                while (true) {
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            System.out.println("executed");
                            // here the swing update
                        }
                    });
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    
    }
    

提交回复
热议问题