与普通线程不同,callable是一个允许返回变量的线程,
我的问题是可以使用可调用线程实现timertask吗?如果是的话,代码是如何工作的?
由于Timer任务正在使用void run()代码,我如何使用可调用对象的timer任务,因为可调用线程使用了对象call(),而不是void run()
例如,我需要实现将返回布尔值的线程(可调用线程可以返回一个布尔值),并且我需要每隔10秒定期运行该线程进程(这就是为什么我要实现计时器任务)
public class test extends TimerTask implements Callable<Boolean>{
public void run() //from timer task thread
{
//timer task will only implement time task in here
// i cant run my task here because my task have return boolean.
// note that run() only accept void task.
}
public boolean call{ // from callable thread
// i implement code here and end result will return true or false
// i have no idea how to instruct timer task
// to keep execute my code here periodically
//task processed . . .
Boolean status = true;
return status;
}
答案
我认为不可能或非常不鼓励在可调用线程上实现计时器任务
答案 0 :(得分:1)
您需要一个Future对象来使用ExecutorService读取结果。
查看示例:
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableTimer {
public static void main(String[] args) {
MyCallableThread myThread = new MyCallableThread();
Timer timer = new Timer();
MyTask theTask = new MyTask();
theTask.addThread(myThread);
// Start in one second and then every 10 seconds
timer.schedule( theTask , 1000, 10000 );
}
}
class MyTask extends TimerTask
{
MyCallableThread timerThread = null;
ExecutorService executor;
public MyTask() {
executor = Executors.newCachedThreadPool();
}
public void addThread ( MyCallableThread thread ) {
this.timerThread = thread;
}
@Override
public void run()
{
System.out.println( "MyTask is doing something." );
if ( timerThread != null ) {
boolean result;
Future<Boolean> resultObject = executor.submit( timerThread );
try {
result = resultObject.get();
System.out.println( "MyTask got " + result + " from Thread.");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
System.out.println( "No Thread set." );
}
}
}
class MyCallableThread implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
Boolean status = true;
System.out.println( "MyCallableThread is returning " + status + ".");
return status;
}
}