Skip to content

Instantly share code, notes, and snippets.

@nida-001
Created September 18, 2013 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nida-001/6609842 to your computer and use it in GitHub Desktop.
Save nida-001/6609842 to your computer and use it in GitHub Desktop.
CAS命令使用版並列奇偶転置ソート
package oddeven;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentOddEvenSort {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int[] array = new int[]{8, 4, 3, 7, 6, 5, 2, 1, -1, 7, 10, 9};
boolean changed = true;
while (changed) {
changed = false;
final ConcurrentHashMap<Boolean, Boolean> map = new ConcurrentHashMap<>(1);
ExecutorService executors = Executors.newFixedThreadPool(8);
for (int i = 0; i < array.length-1; i += 2) {
executors.submit(new Swapper(array, i, map));
}
executors.shutdown();
executors = Executors.newFixedThreadPool(8);
for (int i = 1; i < array.length-1; i+=2) {
executors.submit(new Swapper(array, i, map));
}
executors.shutdown();
changed = map.containsKey(true);
}
System.out.println(Arrays.toString(array));
}
private static class Swapper implements Runnable {
private final int[] array;
private final int i;
private final ConcurrentHashMap<Boolean, Boolean> map;
public Swapper(int[] array, int i, ConcurrentHashMap<Boolean, Boolean> map) {
super();
this.array = array;
this.i = i;
this.map = map;
}
@Override
public void run() {
if (array[i] > array[i+1]) {
final int temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
map.putIfAbsent(true, true);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment