有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用第二个线程停止主线程

我对Java线程有问题。 假设我们有一个名为main的主线程和一个名为Frame的第二个线程。此外,框架还有一个按钮。总的来说,只要按下JFrame中的按钮,我们就有一个循环在运行

我为此写了一个简短的例子,首先是Frame类:

public class Frame extends javax.swing.JFrame{

    private boolean isRunning;

    public Frame() {
        initComponents();
        isRunning = true;
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        isRunning = false;
    }                                        

    public boolean isRunning(){
        return isRunning;
    }

    // ***** Some netbeans stadard stuff *****
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Stop");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(167, 167, 167)
                .addComponent(jButton1)
                .addContainerGap(178, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(153, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(124, 124, 124))
        );

        pack();
    }// </editor-fold>                        



    public void main() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Frame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   

    // ***** End of this netbeans stuff *****
}

现在是主课

public class Main {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Frame f = new Frame();
        f.main();

        for (int i = 0; f.isRunning(); i++) {
            System.out.println((i + 1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

但是,如果我按下按钮,什么都不会发生。我还尝试用“implements Runnable”扩展类框架,重写run()-方法,并在Main中以以下内容开头:

  Thread t = new Thread(new Frame());
  t.start();

但我也有同样的问题

拜托,有人能帮我吗

向马蒂亚斯问好


共 (1) 个答案

  1. # 1 楼答案

    你没有展示正确的Frame

    Main中,您正在创建一个新的Frame实例

    public class Main {
        public static void main(String[] args) {
            Frame f = new Frame();
            f.main();
    
            for (int i = 0; f.isRunning(); i++) {
                // ...
            }
        }
    }
    

    然后在Frame中,你正在创建另一个

    public class Frame extends javax.swing.JFrame{
        // ...
    
        public void main() {
            // ...        
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Frame().setVisible(true);
                }
            });
        }
    
        // ...
    }
    

    Main类中创建的Frame不是出现的那个,这就是为什么f.isRunning()总是返回true。您可以通过显示正确的帧来解决此问题:

    public class Frame extends javax.swing.JFrame{
        // ...
    
        public void main() {
            // ...        
            Frame ref = this;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    ref.setVisible(true);
                }
            });
        }
    
        // ...
    }