线程和计时器有问题。我需要这个方法来执行一些代码,但如果代码需要很长时间,该方法应该返回 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。这个想法是,如果从网络读取需要很长时间,则应该有一个超时。这是最好的方法吗?