Starts a Thread for each element in the List of input Strings and uses Thread.join() to wait for all the Threads to finish. This implementation doesn’t require any Java synchronization mechanisms other than what’s provided by Thread
private volatile List<String> mInput = null; /** * The array of words to find. */ final String[] mWordsToFind; /** * The List of worker Threads that were created. */ private List mWorkerThreads;
Launch process for each and every string
// This List holds Threads so they can be joined when their processing is done. mWorkerThreads = new LinkedList(); // Create and start a Thread for each element in the // mInput. for (int i = 0; i < mInput.size(); ++i) { // Each Thread performs the processing designated by // the processInput() method of the worker Runnable. Thread t = new Thread(makeTask(i)); // Add to the List of Threads to join. mWorkerThreads.add(t); // Start the Thread to process its input in the background. t.start(); }
Barrier synchronization: using thread.join() to wait for the completion of all the other threads
// Barrier synchronization. for (Thread thread : mWorkerThreads) try { thread.join(); } catch (InterruptedException e) { printDebugging("join() interrupted"); }
If t
is a Thread
object whose thread is currently executing,
t.join();
causes the current thread to pause execution until t
‘s thread terminates.
Overloads of join
allow the programmer to specify a waiting period.
Like sleep
, join
responds to an interrupt by exiting with an InterruptedException
.