JAVA:如何在线程中断时停止从API获取数据?

时间:2018-01-12 09:33:36

标签: java multithreading javafx runnable

当我点击开始按钮时,我从twiter api获取数据

点击取消按钮会中断线程,但我仍然可以从twitter api获取数据。

当线程中断时,如何停止从twitter api获取数据?

TryuingRunncabble Class:

public class TryuingRunabble implements Runnable {

    ConnectTwitter coT;

    @Override
    public void run() {
        // TODO Auto-generated method stub

        coT = new ConnectTwitter();
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
            coT.searchtwitter();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException
                | TwitterException | SQLException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

MainControll类:

TryuingRunabble r = new TryuingRunabble();

@Override
public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub

    start.addEventHandler(MouseEvent.MOUSE_CLICKED, (e)->{
        r.run();    
    });


    stop.addEventHandler(MouseEvent.MOUSE_CLICKED, (e)->{
        Thread.currentThread().interrupt();

    });

}

1 个答案:

答案 0 :(得分:0)

您需要中断Thread正在运行的TryuingRunabble

    TryuingRunabble r = new TryuingRunabble();
    Thread t = new Thread(r);

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub

        start.addEventHandler(MouseEvent.MOUSE_CLICKED, (e)->{
            t.start();
        });


        stop.addEventHandler(MouseEvent.MOUSE_CLICKED, (e)->{
            t.interrupt();
        });
    }