Assuming that this is the scenario:
class A extends TimerTask{
int a;
public void run(){
//operation to be performed periodically
}
}
and
class B{
int delay=2000,interval=3000;
A objectA;
public static void main(String[] args){
Timer t=new Timer();
t.scheduleAtFixedRate(new A(),delay,interval);
}
}
Can't run() return objects? If I make such a change, incompatibility is cited. Why?
As you can see in the method-declaration, the returntype of run is void. Therefore the method can't directly return an object. But what you can do, is storing an object at the instance-level of class A and declaring a method on A from which you can get the stored object, when it's operation is finished
Use a FutureTask (and Future) with ExecutorService (see examples on API pages).
public static void main(String[] args) throws Exception {
FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {
public String call() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello World!";
}
});
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(future);
System.out.println(future.get());
}
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