Java: How to use Thread.join
Use something like this:
public void executeMultiThread(int numThreads)
throws Exception
{
List threads = new ArrayList();
for (int i = 0; i < numThreads; i++)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
// do your work
}
});
// System.out.println("STARTING: " + t);
t.start();
threads.add(t);
}
for (int i = 0; i < threads.size(); i++)
{
// Big number to wait so this can be debugged
// System.out.println("JOINING: " + threads.get(i));
((Thread)threads.get(i)).join(1000000);
}
With otherThread being the other thread, you can do something like this:
@Override
public void run() {
int i = 0;
int half = (info.size() / 2);
for (String s : info) {
i++;
if (i == half) {
try {
otherThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s %s%n", getName(), s);
Thread.yield(); //Give other threads a chance to do their work
}
}
The Java-tutorial from Sun: http://java.sun.com/docs/books/tutorial/essential/concurrency/join.html