如何启动和停止线程

时间:2019-05-01 09:35:33

标签: java multithreading networking

我正在设置一个新程序。通过单击程序中的开始按钮,我想启动线程,然后单击停止按钮来停止。因此,开始按钮启动线程,停止按钮停止。我应该如何转换代码才能正常工作?我只需要使用一个线程。

public class server implements Runnable, ActionListener {

    JFrame frame;
    JButton button1;
    JButton button2;

    public void makeFrame() {
        frame = new JFrame("Frame");
        frame.setSize(1000, 500);
        frame.getContentPane().setBackground(new Color(74, 74, 74)); 
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null); 
        frame.setVisible(true); 
        frame.setLayout(null);
    }

    public void makeButtons() {
        gomb1 = new JButton("Indítás");
        gomb1.setBounds(350, 300, 100, 30);  
        gomb1.setBackground(new Color(127, 127, 127)); 
        frame.getContentPane().add(gomb1);
        gomb1.addActionListener(this);

        gomb2 = new JButton("Stop");
        gomb2.setBounds(550, 300, 100, 30); 
        gomb2.setBackground(new Color(127, 127, 127));
        frame.getContentPane().add(gomb2);

    }

    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == button1) {

        }
    }



    @Override
    public void run() {
        try {
            go();
        } catch (InterruptedException ex) {
            Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public void go() throws InterruptedException {
        doMore();
    }

    public void doMore() throws InterruptedException {

        for (int i = 0; i < 20; i++) {
            System.out.println("Fut a thread" + i);

        }

    }
}

class Test {    

    public static void main(String[] args) {
        server t = new server();
        t.makeFrame();
        t.makeButtons();
        Runnable r = new server();
        Thread szal = new Thread(r);
        Thread szal2 = new Thread(r);

        szal.start();
        szal2.start();
    }
}

0 个答案:

没有答案
相关问题