如何保持方法在后台连续运行直到程序结束?

如何保持方法在后台连续运行直到程序结束?,第1张

如何保持方法在后台连续运行直到程序结束?

以最简单的方式,您可能会遇到以下情况:

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();     } }        }    }}

编辑


添加了带有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<Object, Object> {        @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();     } }        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5587274.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存