⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testthread.java

📁 本人大二学习汇编语言程序设计时的全部源代码
💻 JAVA
字号:

public class TestThread {
	
	public static int[] initArray(int num) {
		int[] a = new int[num];
		for (int i = 0; i < num - 1; i++) {
			a[i] = (int) (10*Math.random() + 100*Math.random()+ 1000*Math.random());
		}
		return a;
	}
	
	public static void printArray(int[] a) {
		System.out.print("前十位:");
		for(int i = 0; i<10; i++) {
			System.out.print(a[i] + " ");
		}
		System.out.println("");
		System.out.print("后十位:");
		for(int i = a.length-10; i<a.length-1; i++) {
			System.out.print(a[i] + " ");
		}
		
	}	

	public static void main(String[] args) {
		int[] a = TestThread.initArray(20000);
		int[] b = new int[a.length];
		for(int i=0; i<a.length-1; i++) {
			b[i] = a[i];
		}
		BubbleThread bt = new BubbleThread();
		InsertThread it = new InsertThread();
		bt.start();
		it.start();
		it.insertSortTime(a);
		bt.bubbleSortTime(b);
	}
}

//可以实现Runnable接口,为了方便直接继承Thread
class BubbleThread extends Thread {
	//也可以重写run方法,在run方法中调用排序算法	
	public synchronized void bubbleSort(int[] a) {
		int i, k, temp;
		int len = a.length;
		for (i = 0; i < len - 1; i++)
			for (k = len - 1; k > i; k--)
				if (a[k] < a[k - 1]) {
					temp = a[k - 1];
					a[k - 1] = a[k];
					a[k] = temp;
				}
	}

	public synchronized void bubbleSortTime(int[] a) {
		double start, end, time;
		System.out.println("排序前:");
		TestThread.printArray(a);
		start = System.currentTimeMillis();
		bubbleSort(a);
		end = System.currentTimeMillis();
		time = end - start;
		System.out.println("\n排序后:");
		TestThread.printArray(a);
		System.out.println("使用冒泡排序消耗的时间:" + time + "\n");
	}

}

class InsertThread extends Thread {
		
	public synchronized void insertSort(int[] a) {
		int i, j, temp;
		int len = a.length;
		for (i = 1; i < len - 1; i++) {
			temp = a[i];
			j = i - 1;
			while ((j >= 0) && (temp < a[j])) {
				a[j + 1] = a[j];
				j--;
			}
			if (j != (i - 1))
				a[j + 1] = temp;
		}
	}

	public synchronized void insertSortTime(int[] a) {
		double start, end, time;
		System.out.println("排序前:");
		TestThread.printArray(a);		
		start = System.currentTimeMillis();
		insertSort(a);
		end = System.currentTimeMillis();
		time = end - start;
		System.out.println("\n排序后:");
		TestThread.printArray(a);
		System.out.println("使用直接插入排序消耗的时间:" + time + "\n");
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -