Hello Everyone,
I have tried reading up on
Thread Sync which the basics I'm pretty sure I understand. In my project I have 2 arrays of thread objects, we will say Aobj1 and Aobj2, on execution of my project the first thing I do is create Aobj1 and start the threads. Afterwards my project creates separate threads and adds them to Aobj2, during which time Aobj1's threads are polling Aobj2 to see if any threads are available. If there are, then 1 of the threads running under Aobj1 grabs the new thread from Aobj2 array and starts the new thread. (Hope you are still with me)
The problem I am having is, how do I synch these up and what am I synching on? (below is code to help) Also I'm not a guru when it comes to
Java so some stuff may come over incorrectly (java terminology) I do apologies for that in advance. I also noticed the post doesn't keep the format either, sorry about that too..
So just to rehash here, I am not sure where or how to get everything in sync, do I need to sync the secondThreadList with anything or can those run without? I am pretty sure syncing Main with myThreads is a must because I get the following error (java.lang.IllegalMonitorStateException) which I know means the threads are not locked into my Main (I am guessing) due to the wait();
Also I have to use wait(), notifyAll() in this project.
Thanks for the help
Justin
// array that holds secondary threads //
private ArrayList<MYRunnable> secondThreadList = new ArrayList<MYRunnable>();
Main Constructor:
// in my main constructor I init 6 threads. MYThread's constructor starts the thread
for(i = 0; i < 6; i++) {
myThreads[i] = new MYThread(secondThreadList, Integer.toString(i));
}
Main:
// I have a loop that generates separate threads and adds them to an array, these are NOT started at creation time
myrunnable = new MYRunnable();
secondThreadList.add(myrunnable);
// once the new thread is in the array I notify all of the running threads which will check the array and pull the new thread off and start it//
notifyAll();
MyThread:
// in my run method I have the following, which polls the thread array and if its 0 then it waits, otherwise it will execute the new thread
while(mysecondThreadList.size() == 0)
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Running request in thread: " + threadId);
MYRunnable runnable = mysecondThreadList.get(0);
mysecondThreadList.remove(0);
runnable.myrun.start(); // myrun is the name of thread variable