简体   繁体   中英

JAVA: How to stop fetching data from API when thread is interrupted?

When i click on start button i get data from twiter api

Clicking on the cancel button interrupts the thread but i still get data from twitter api.

How do i stop getting data from twitter api when thread is interrupted?

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 Class:

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();

    });

}

You need to interrupt the Thread running 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();
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM