JAVA: 如何在线程中断时停止从API 获取数据?
JAVA: How to stop fetching data from API when thread is interrupted?
当我点击开始按钮时,我从推特上获取数据 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 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();
});
}
你需要打断 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();
});
}
当我点击开始按钮时,我从推特上获取数据 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 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();
});
}
你需要打断 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();
});
}