java - Multithreading concept -


i learning multi-threading concepts now. can run single thread of handler , runnable(). want code run 2 threads, thread1 runs method1() , thread2 runs method2(). thread1 should run 2seconds , sleep 1second. in mean time, thread2 should wakeup , run 1second. again, thread1 should run 2seconds. process should done continuously. doing in android.

the question might straight forward, have no other way, other posting question here, have gone through many tutorials , questions in website. no post suits context. suggestions appreciated. in advance.

you can using scheduledthreadpoolexecutor, can achieve parallel execution of tasks. small sample example schedule tasks:

//creates thread pool of size 2 int poolsize = 2; // creates scheduledthreadpoolexecutor object number of thread 2 scheduledthreadpoolexecutor exec = new scheduledthreadpoolexecutor(poolsize);  //starts executing after 1 second scheduledfuture<callable-type> sf = stpe.schedule(new taskone(), 1,timeunit.seconds);  //starts executing after 2 seconds scheduledfuture<callable-type> sf1 = stpe.schedule(new tasktwo(), 2,timeunit.seconds); 

and can define tasks below:

class taskone implements callable<callable-type> {     @override     public callable-type call() throws exception {         //do work here         return callable-type;     } }  class tasktwo implements callable<callable-type> {         @override         public callable-type call() throws exception {             //do work here             return callable-type;         }     } 

the advantages of using scheduledthreadpoolexecutor on timer :

  • a timer creates single thread executing timer tasks. scheduled thread pools address limitation letting provide multiple threads executing deferred , periodic tasks.
  • another problem timer behaves poorly if timertask throws unchecked exception. timer thread doesn't catch exception, unchecked exception thrown timertask terminates timer thread.

ref: java concurrency in practice


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -