在Runnable中停止TimerTask

时间:2015-04-14 12:22:58

标签: java multithreading sockets timer

我已经卡住了,不知道如何在我的程序中停止2个Timer。我有一个Thread用socket初始化连接,然后我有两个Runnables,一个用于InputStream,一个用于OutputStream这是我的代码:

public class Receiver extends Thread {
public void run() {

        initializeThreads();

    }

public static void initializeThreads() {

        try {

            // create new thread pool with four threads
            application = Executors.newCachedThreadPool();
            // create ArrayBlockQueueSync to store ints
            Buffer sharedLocation = new ArrayBlockQueueSync();
            // execute tasks
            application.submit(new Reader(client.getInputStream(), sharedLocation));
            application.submit(new Writer(client.getOutputStream(), sharedLocation));
            application.submit(new MyTimer1(sharedLocation));
            application.submit(new MyTimer2(sharedLocation));

        } catch (IOException e) {
            WriteExceptions.writeToFile(e);
            System.err.println("Error on the run Receiver.\n" + e);
        }

    }

    public static void disconnect() {
        try {
            client.close();
            System.out.println("Close Socket");
            shutdownAndAwaitTermination();
        } catch (IOException e) {
            e.printStackTrace();
            WriteExceptions.writeToFile(e);
        }
    }
    // This I found on the javadoc
    public static void shutdownAndAwaitTermination() {
        application.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!application.awaitTermination(60, TimeUnit.SECONDS)) {
                application.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!application.awaitTermination(60, TimeUnit.SECONDS))
                    System.err.println("Pool did not terminate");
            }
        } catch (InterruptedException ie) {
            WriteExceptions.writeToFile(ie);
            // (Re-)Cancel if current thread also interrupted
            application.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
}

作家和读者如下:

public class Writer implements Runnable {
    @Override
    public void run() {
        try {

            while (!Thread.interrupted()) {
                // read or write the socket
            }

        }
}

计时器就像这样:

public class Timer1 implements Runnable {
    @Override
    public void run() {
        try {
            // Declare the timer
            Timer t = new Timer();
            // Set the schedule function and rate
            t.scheduleAtFixedRate(new TimerTask() {

                @Override
                public void run() {
                    // perform my task
                    } catch (InterruptedException e) {
                        WriteExceptions.writeToFile(e);
                    }
                }

            },5 * 60 * 1000,24 * 60 * 60 * 1000);


        } catch (Exception ex) {
            WriteExceptions.writeToFile(ex);
        }
    }
}

我的问题,当我调用Receiver的断开方法时,计时器没有停止。谢谢

1 个答案:

答案 0 :(得分:0)

感谢@fge建议,我使用ScheduledExecutorService类并且工作正常。