我创建了一个启动线程的GUI,它可以做一些非常简单的事情。但是,子线程永远不会启动。子线程不启动
子线程,如果启动,将提供一些输出;尽管我没有得到任何输出。我错过了什么?
下面的代码:
的GUI类:
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class gui { public static void main(String [] args) { //final standalone s = new standalone(); final try2 t= new try2(); JFrame win = new JFrame(); win.setLayout(new FlowLayout()); JButton start = new JButton("Start"); JButton stop = new JButton("Stop"); start.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub t.t.start(); System.out.println("M on!"); try{ Thread.currentThread().sleep(10000); }catch(Exception e1) { e1.printStackTrace(); } System.out.println("M off!"); if(t.t.isInterrupted()) System.out.println("Stopped"); } }); win.add(start); win.add(stop); win.setVisible(true); } }
这里是子线程
public class try2 implements Runnable { public Thread t; int i; try2() { t=new Thread(); } public void run() { System.out.println(++i); } }
脱离主题的建议:阅读Java命名约定。类应该被命名为“LikeThisName”,而不是“likethisname”。 – bezmax 2012-03-21 07:48:37
您没有覆盖try2.t中的运行方法 – styfle 2012-03-21 07:49:59
您可以在线程上加入()以等待它结束,而不是睡眠10秒。 – 2012-03-21 09:31:11