unlike common thread, a callable is a thread that allow a return variable,
my question is can timertask implemented with callable thread? if yes, how does the code work?
As Timer task is using void run() for it code, how can i used timer task with callable object because callable thread used object call(), not void run()
As example, i need to implement thread which will return a boolean value (Callable thread can return a boolean value), and i need to made that thread process run periodically every 10 second (which is why i want to implement timer task)
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;
}
Answer
I assume not possibloe or highly discourage to implement timer task on callable thread
You need a Future object to read the result with ExecutorService.
Look on the example:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With