How to make a particular thread to start among other threads of same priority? For example I have 5 threads T1, T2 ~ T5 and all are having same priority. How would I go, if I want to have the thread say T3 to execute first among T1 ~ T5.
What do you mean by "execute first"? You want to run one thread, then another? Then just don't run them at the same time, run one and when it's finished run the other one. But probably that wasn't what you meant... so what exactly did you mean?
Joined: May 29, 2007
I wanted to know how to make a particular thread to run first among a group of threads having same priority. If all the threads are having the same priority, it is scheduler which takes care of which thread to run. I was curious to know whether it is possible to control a particular thread to run thru java code. For example there are 5 threads T1 ~T5 of same priority. The scheduler may decide to run any one of these threads first, it could be either T1 or T2 or T3 or T4 or T5. Suppose I want to run the thread T3 ahead ( to start first) of other threads, how is it possible thru java code?
With Java you cannot command or make a particular thread run. You can only use thread communication tools like synchronized blocks, locks, semaphores etc. and shared objects. So what I would do is :
1) initialize each thread (or runnable) with an unique number, eg. T1 - 1, T2 - 2 etc.
2) make all the threads wait on a common lock L
3) set a shared integer to a desired value, eg. i = 3
4) release all of the threads at once
5) have each thread check what's the current number. If it is the same as the thread's number, carry on, if not - sleep again (wait on the lock)
Be sure to synchronize access to i properly.