2012-03-21 31 views
0

我创建了一个启动线程的GUI,它可以做一些非常简单的事情。但是,子线程永远不会启动。子线程不启动

子线程,如果启动,将提供一些输出;尽管我没有得到任何输出。我错过了什么?

下面的代码:

  1. 的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); 
        } 
    } 
    
  2. 这里是子线程

    public class try2 implements Runnable { 
        public Thread t; 
        int i; 
    
        try2() { 
         t=new Thread();    
        } 
    
        public void run() { 
         System.out.println(++i); 
        } 
    } 
    
+0

脱离主题的建议:阅读Java命名约定。类应该被命名为“LikeThisName”,而不是“likethisname”。 – bezmax 2012-03-21 07:48:37

+0

您没有覆盖try2.t中的运行方法 – styfle 2012-03-21 07:49:59

+0

您可以在线程上加入()以等待它结束,而不是睡眠10秒。 – 2012-03-21 09:31:11

回答

1

使类try2扩展Thread(并删除即时消息请致电Runnable),然后只需在您的try2实例上调用start()即可。

+1

扩展'线程'不是最佳实践。你应该实现'Runnable'并把它放到'Thread'的构造函数中。这里的解释:http://stackoverflow.com/questions/541487/java-implements-runnable-vs-extends-thread – bezmax 2012-03-21 07:52:27

+0

这也是我的偏好,但对于这样一个简单的情况,这有点矫枉过正。 – 2012-03-21 08:02:04

+1

不是。而不是'threadObject.start()'你写'新线程(runnableObject).start()'。没有那么多的矫枉过正。一个矫枉过正的做法是使用'ExecutorService'(这实际上是首选)来执行这样简单的任务。 – bezmax 2012-03-21 08:04:07

3

当您致电t.t.start()时,它将启动try2对象的t字段中的线程对象。不幸的是,这个线程没有Runnable,所以当你启动它时,它会立即退出。不调用try2.run()方法,因为线程对此一无所知。

您的代码很复杂。我会简化/修复它如下:

  1. 摆脱try2.t字段。

  2. actionPerformed方法创建和运行线程如下:

    new Thread(t).start(); 
    

    其中t是你try2实例。

虽然在修复代码时,try2违反了我所遇到过的所有Java风格指南。类名应始终以大写字母开头。养成这样做的习惯吧...

0

你的类try2应该扩展Thread(并实现run()方法) 你正在处理它的方式,yuo正在调用run()方法try2中的线程对象t。但是这个对象的run()方法是空的。

+0

扩展'Thread'是个不错的主意。实现'Runnable'是一个首选的方法。更多信息在这里:http:// stackoverflow。com/questions/541487/java-implements -unnnable-vs-extends-thread – bezmax 2012-03-21 07:53:27

+0

感谢您提供此信息。到现在为止还没有想过...... – AlexS 2012-03-21 10:51:58