
以最简单的方式,您可能会遇到以下情况:
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(); } } } }}欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)