我得到一些异常,我需要知道程序何时关闭,因为我需要关闭套接字.
我有默认的公共静态main方法,我不断重复一个动作和一个Thread类.
private static Thread thread;
public static boolean isRunning = true;
public static void main(String[] args){
thread = new Thread(new ThreadListenServer());
thread.start();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run(){
// some action
}
}
timer.scheduleAtFixedRate(task, 0, 10000);
isRunning = false;
}
以及在后台运行的线程类:
public class ThreadListenServer implements Runnable{
private DatagramSocket socket;
public ThreadListenServer() throws SocketException{
socket = new DatagramSocket(6655);
}
@Override
public void run() {
while(MainProgram.isRunning){
// some action
}
socket.close();
}
}
我不知道为什么,但是它正在变得虚假,但它不应该.如果主程序关闭,我该如何关闭套接字? (这是因为即使程序关闭,线程仍然在后台运行).
我正在考虑在主类中创建套接字然后我将套接字对象作为参数传递给ThreadClass,如果程序关闭,我也应该关闭套接字.