用第二个Thread停止main-Thread

时间:2017-03-03 18:34:13

标签: java multithreading

我遇到了Java Threads的问题。 假设我们有一个名为Main的主线程和一个名为Frame的第二个线程。此外,Frame有一个JButton。在Main中,我们有一个循环,只要在JFrame中按下Button就会运行。

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

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 *****
}

现在是Main-Class

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”扩展Class Frame并覆盖run() - Method并在Main中启动它:

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

但是我遇到了同样的问题。

拜托,有人可以帮助我吗?

最好的问候马蒂亚斯

1 个答案:

答案 0 :(得分:0)

您没有显示正确的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);
            }
        });
    }

    // ...
}

您在Frame课程中创建的Main不是出现的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); } }); } // ... } {1}}。您可以通过显示正确的框架来解决此问题:

extension UIImage {

    func crop(withPath: UIBezierPath, andColor: UIColor) -> UIImage {
        let r: CGRect = withPath.cgPath.boundingBox
        UIGraphicsBeginImageContextWithOptions(r.size, false, self.scale)
        if let context = UIGraphicsGetCurrentContext() {
            let rect = CGRect(origin: .zero, size: size)
            context.setFillColor(andColor.cgColor)
            context.fill(rect)
            context.translateBy(x: -r.origin.x, y: -r.origin.y)
            context.addPath(withPath.cgPath)
            context.clip()
        }
        draw(in: CGRect(origin: .zero, size: size))
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            return UIImage()
        }
        UIGraphicsEndImageContext()
        return image
    }

}