Advertisement
Guest User

Untitled

a guest
Apr 20th, 2014
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. public class test extends TimerTask implements Callable<Boolean>{
  2.  
  3. public void run() //from timer task thread
  4. {
  5. //timer task will only implement time task in here
  6. // i cant run my task here because my task have return boolean.
  7. // note that run() only accept void task.
  8. }
  9.  
  10. public boolean call{ // from callable thread
  11. // i implement code here and end result will return true or false
  12. // i have no idea how to instruct timer task
  13. // to keep execute my code here periodically
  14.  
  15. //task processed . . .
  16. Boolean status = true;
  17.  
  18.  
  19. return status;
  20. }
  21.  
  22. import java.util.Timer;
  23. import java.util.TimerTask;
  24. import java.util.concurrent.Callable;
  25. import java.util.concurrent.ExecutionException;
  26. import java.util.concurrent.ExecutorService;
  27. import java.util.concurrent.Executors;
  28. import java.util.concurrent.Future;
  29.  
  30. public class CallableTimer {
  31.  
  32. public static void main(String[] args) {
  33. MyCallableThread myThread = new MyCallableThread();
  34. Timer timer = new Timer();
  35. MyTask theTask = new MyTask();
  36. theTask.addThread(myThread);
  37.  
  38. // Start in one second and then every 10 seconds
  39. timer.schedule( theTask , 1000, 10000 );
  40. }
  41. }
  42.  
  43. class MyTask extends TimerTask
  44. {
  45. MyCallableThread timerThread = null;
  46. ExecutorService executor;
  47.  
  48. public MyTask() {
  49. executor = Executors.newCachedThreadPool();
  50. }
  51.  
  52. public void addThread ( MyCallableThread thread ) {
  53. this.timerThread = thread;
  54. }
  55.  
  56. @Override
  57. public void run()
  58. {
  59. System.out.println( "MyTask is doing something." );
  60. if ( timerThread != null ) {
  61. boolean result;
  62. Future<Boolean> resultObject = executor.submit( timerThread );
  63.  
  64. try {
  65. result = resultObject.get();
  66. System.out.println( "MyTask got " + result + " from Thread.");
  67. } catch (InterruptedException e) {
  68. e.printStackTrace();
  69. } catch (ExecutionException e) {
  70. e.printStackTrace();
  71. }
  72. } else {
  73. System.out.println( "No Thread set." );
  74. }
  75. }
  76.  
  77. }
  78.  
  79. class MyCallableThread implements Callable<Boolean> {
  80.  
  81. @Override
  82. public Boolean call() throws Exception {
  83. Boolean status = true;
  84. System.out.println( "MyCallableThread is returning " + status + ".");
  85. return status;
  86.  
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement