linux 并行 排序,并行奇偶排序

编程入门 行业动态 更新时间:2024-10-24 18:17:48

linux 并行 排序,并行<a href=https://www.elefans.com/category/jswz/34/1748748.html style=奇偶排序"/>

linux 并行 排序,并行奇偶排序

package sort.odd_even;

/**

* Created By Corleone

* Created at 2018年2月4日 下午7:40:14

*/

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

/**

* @author Corleone

* @created at 2018年2月4日下午7:40:14

*/

public class OddEvenSortParall {

static int exchangeFlag = 1;

static ExecutorService pool = Executors.newCachedThreadPool();

static int[] array = { 1, 4, 2, 6, 35, 3 };

static synchronized void setExchangeFlag(int v) {

exchangeFlag = v;

}

static synchronized int getExchangeFlag() {

return exchangeFlag;

}

public static class OddEventSortTask implements Runnable {

int i;

CountDownLatch latch;

public OddEventSortTask(int i, CountDownLatch latch) {

this.i = i;

this.latch = latch;

}

public void run() {

if (array[i] > array[i + 1]) {

int temp = array[i];

array[i] = array[i + 1];

array[i + 1] = temp;

setExchangeFlag(1);

}

latch.countDown();

}

}

public static void pOddEventSort(int[] arr) throws InterruptedException {

int start = 0;

while (getExchangeFlag() == 1 || start == 1) {

setExchangeFlag(0);

// 偶数的数组长度,当start=1时候,只有len/2-1 个线程

CountDownLatch latch = new CountDownLatch(arr.length / 2 - (arr.length % 2 == 0 ? start : 0));

for (int i = start; i < arr.length; i += 2) {

pool.submit(new OddEventSortTask(i, latch));

}

// 等待所有县城结束

latch.await();

if (start == 0) {

start = 1;

} else {

start = 0;

}

}

}

public static void main(String[] args) throws InterruptedException {

pOddEventSort(array);

for (int ar : array) {

System.out.println(ar);

}

}

}

更多推荐

linux 并行 排序,并行奇偶排序

本文发布于:2024-02-14 11:08:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1763277.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:奇偶   linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!