Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing threads to do multiple things without having a thread for each
    text
    copied!<p>I have a class which basically does the same series of steps twice. Sounds like a perfect example of where to multithread your program. My question is though if I can do this with only two threads. Here is the general jist of things</p> <pre><code>Tester implements Runnable{ Thread obj1Thread, obj2Thread; MyObj obj1, obj2; String obj1Results, obj2Results; void runTests(){ obj1Thread = new Thread(this, "ob1 thread"); obj2Thread = new Thread(this, "ob2 thread"); obj1.start();//builds up obj1 obj2.start();//builds up obj2 if(obj1 and obj2 are finished building){ System.out.println(obj1); System.out.println(obj2); } obj1Thread.startSecondPhase()//runs a separate function that tests obj1 vs ob2. Essentially test(ob1, ob2) obj2Thread.startSecondPhase()//runs a separate function that tests obj2 vs ob1. Essentially test(ob2, ob1) if(obj1 and obj2 are finished testing){ System.out.println(obj1Results); System.out.println(obj2Results); } } } </code></pre> <p>I have gotten the first part - building up the objects - working. My questions are now - </p> <ol> <li>How can I get the main thread to wait for the two threads to finish their first part? Perhaps the main would do a <code>wait</code> on both objects and then after the threads <code>notifyAll</code> they do a wait on the main thread? But then how do the threads get a hold of the main thread? Perhaps with <code>this</code>?</li> <li>How can I have this 'second phase' of the run function without making a new class with a new thread and a new specific run function? I dont want to have to make a new class and everything for every little task.</li> </ol> <p>To clarify the sequence of events I want specifically is - </p> <ol> <li>Main thread initializes and starts two threads</li> <li>Both threads simultaneously build their respective objects</li> <li>When both threads finish building they pause. Then main thread prints the objects out in order.</li> <li>After main thread is done, the two threads continue their code to a testing phase simultaneously </li> <li>When the threads are done the main thread prints the results out. Could probably use a <code>join()</code> here</li> </ol> <p>Edit: Also, how can I tell the specific threads which objects I want them to work on? Right now Im doing it in a kinda hacky way (i'm working off the thread name). </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload