1

线程和计时器有问题。我需要这个方法来执行一些代码,但如果代码需要很长时间,该方法应该返回 false。这是我正在做的事情:

    public boolean handShake() {

        java.util.Timer t = new java.util.Timer();
    t.schedule(new java.util.TimerTask() {
            public void run() {
                if (threadSuccess = false) {
                    System.out.println("will kill");
//not sure but this is how I read you should kill threads?
                    Thread t = handShakeThread;
                    handShakeThread = null;
                    t.interrupt();
                    System.out.println("Should have killed thread");
                }
            }
        }, 8000);

        try {
            System.out.println("Going to start threads");

            handShakeThread = new Thread(new HandShakeThread());
//handShakeThread is a field (Threat) and HandShakeThread is a class extending Runnable
            handShakeThread.start();
        System.out.println("Thread started");
            handShakeThread.join();
            System.out.println("finished");
            return threadSuccess;
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            return false;
        }
    }

计时器任务似乎从未被调用。它坐在那里等待和等待。我能做些什么?

额外信息:handShakeThread 正在从网络读取。如果成功完成读取,则将字段 threadSuccess 设置为 true。这个想法是,如果从网络读取需要很长时间,则应该有一个超时。这是最好的方法吗?

4

1 回答 1

3

尝试将您的 HandShakeThread 重写为 Runnable 并执行类似的操作。如果 Runnable 在 8 秒后没有完成,该方法将返回 false。

public boolean handShake() {
    Runnable handShakeTask = new Runnable() {
        @Override
        public void run() {
            // do network stuff
        }
    };
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    try {
        Future<Boolean> future = executorService.submit(networkTask, true);
        executorService.shutdown();
        return future.get(8, TimeUnit.SECONDS);
    } catch (TimeoutException ex) {
        return false;
    } catch (InterruptedException | ExecutionException e) {
        // handle exception
    } 
}
于 2013-04-29T02:31:25.657 回答