I think this is a good exercise in thread management, where (1) the task can be divided into several parts (2) the parts can be executed independently and asynchronously and (3) the main thread controls the completion of all such tasks in the corresponding threads. All you need is for this main thread to wait () and be notified () - ed by the task when the thread terminates each time. Here is an example of code that you can compile / run. Uncomment println () to see more.
Notes: [1] The JVM does not guarantee the execution order of the threads [2]. You need to synchronize when your main thread accesses a large array so as not to have any corrupted data ....
public class ShufflingArray {
private int nPart = 4, // Count of jobs distributed, resource dependent activeThreadCount, // Currently active, monitored with notify iRay[]; // Array the threads will work on public ShufflingArray (int[] a) { iRay = a; printArray (a); } private void printArray (int[] ia) { for (int i = 0 ; i < ia.length ; i++) System.out.print (" " + ((ia[i] < 10) ? " " : "") + ia[i]); System.out.println(); } public void shuffle () { int startNext = 0, pLen = iRay.length / nPart; // make a bunch of parts for (int i = 0 ; i < nPart ; i++, activeThreadCount++) { int start = (i == 0) ? 0 : startNext, stop = start + pLen; startNext = stop; if (i == (nPart-1)) stop = iRay.length; new Thread (new ShuffleOnePart (start, stop, (i+1))).start(); } waitOnShufflers (0); // returns when activeThreadCount == 0 printArray (iRay); } synchronized private void waitOnShufflers (int bump) { if (bump == 0) { while (activeThreadCount > 0) { // System.out.println ("Waiting on " + activeThreadCount + " threads"); try { wait(); } catch (InterruptedException intex) { }}} else { activeThreadCount += bump; notify(); }} public class ShuffleOnePart implements Runnable { private int startIndex, stopIndex; // Operate on global array iRay public ShuffleOnePart (int i, int j, int k) { startIndex = i; stopIndex = j; // System.out.println ("Shuffler part #" + k); } // Suppose shuffling means interchanging the first and last pairs public void run () { int tmp = iRay[startIndex+1]; iRay[startIndex+1] = iRay[startIndex]; iRay[startIndex] = tmp; tmp = iRay[stopIndex-1]; iRay[stopIndex-1] = iRay[stopIndex-2]; iRay[stopIndex-2] = tmp; try { // Lets imagine it needs to do something else too Thread.sleep (157); } catch (InterruptedException iex) { } waitOnShufflers (-1); }} public static void main (String[] args) { int n = 25, ia[] = new int[n]; for (int i = 0 ; i < n ; i++) ia[i] = i+1; new ShufflingArray(ia).shuffle();
}}
Manidip sengupta
source share