Java多线程实现归并排序

Java中,一个class可以继承Thread类以实现多线程调用

import java.util.*;
import java.util.stream.*;
class Worker extends Thread {
	int[] data = null;
	public Worker() {
		super();
	}
	void setData(int[] data) {
		this.data = data;
	}
	int[] getData() {
		return this.data;
	}
	public void run() {
		if (data.length <= 10) {
			for (int i=0;i<data.length;i++) {
				for (int j=i+1;j<data.length;j++) {
					if (data[i] > data[j]) {
						int t = data[i];
						data[i] = data[j];
						data[j] = t;
					}
				}
			}
		}else {
			int[] first = Arrays.copyOfRange(this.data,0,this.data.length/2);
			int[] second = Arrays.copyOfRange(this.data,this.data.length/2,this.data.length);
			Worker firstWorker = new Worker();
			Worker secondWorker = new Worker();
			firstWorker.setData(first);
			secondWorker.setData(second);
			firstWorker.start();
			secondWorker.start();
			try{
				firstWorker.join();
				secondWorker.join();
			}catch(InterruptedException e) {
			}
			int pos = 0;
			int pos1 = 0, pos2 = 0;
			first = firstWorker.getData();
			second = secondWorker.getData();
			while (true) {
				if (first.length == pos1 && second.length == pos2) {
					break;
				}
				if (first.length == pos1) {
					data[pos++] = second[pos2++];
					continue;
				}
				if (second.length == pos2) {
					data[pos++] = first[pos1++];
					continue;
				}
				if (first[pos1] < second[pos2]) {
					data[pos++] = first[pos1++];
				}else {
					data[pos++] = second[pos2++];
				}
			}
		}
	}
	void printData() {
		for (int w : data) {
			System.out.print(w + " ");
		}
		System.out.println();
	}
}

class Main {
	public static void main(String args[]) {
		int n = 1000;
		int[] data = new Random().ints().map(x->x%100000).limit(n).toArray();
		Worker worker = new Worker();
		worker.setData(data);
		System.out.println("The Original Array is:");
		worker.printData();
		worker.start();
		try {
			worker.join();
		} catch(InterruptedException e) {
			System.out.println(e);
		}
		System.out.println("The Sorted Array is:");
		worker.printData();
	}
};

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据