实验十 多线程
实验目的
1.线程的概念、线程的生命周期。
2.多线程的编程:继承 Thread 类与使用 Runnable 接口。
主要仪器设备及耗材
安装了 JDK1.8 的 PC 一台
实验内容
1. 将插入、冒泡排序算法设计成线程,启动两个以上不同的线程同时运行,计算不同排序
的运行时间。
package com.temp;
import java.util.Random;
/**
* @Author lanxiaofang
* @email [email protected]
* @date 2020/11/27 19:57
* 1. 将插入、冒泡排序算法设计成线程,启动两个以上不同的线程同时运行,计算不同排序的运行时间。
*/
public class RimingTimeOfAlgorithm extends Thread {
private static final int Length = 10000;
private static int array[] = new int[Length];
private long startTime, endTime;
public RimingTimeOfAlgorithm(String name) {
super(name);
}
public static void main(String[] args) {
Random random = new Random(System.nanoTime());
for (int i = 0; i < Length; i++) {
array[i] = random.nextInt(Length);
System.out.print(" " + array[i]);
}
System.out.println("\n------------随机数输出完毕---------------");
RimingTimeOfAlgorithm rtoa1 = new RimingTimeOfAlgorithm("Thread 1");
RimingTimeOfAlgorithm rtoa2 = new RimingTimeOfAlgorithm("Thread 2");
RimingTimeOfAlgorithm rtoa3 = new RimingTimeOfAlgorithm("Thread 3");
RimingTimeOfAlgorithm rtoa4 = new RimingTimeOfAlgorithm("Thread 4");
RimingTimeOfAlgorithm rtoa5 = new RimingTimeOfAlgorithm("Thread 5");
RimingTimeOfAlgorithm rtoa6 = new RimingTimeOfAlgorithm("Thread 6");
rtoa1.bubble();
rtoa2.insert();
rtoa3.bubble();
rtoa4.insert();
rtoa5.bubble();
rtoa6.insert();
}
void bubble() {
BubbleSort bubbleSort = new BubbleSort();
bubbleSort.start();
}
void insert() {
InsertSort insertSort = new InsertSort();
insertSort.start();
}
class BubbleSort extends Thread {
@Override
public void run() {
startTime = System.currentTimeMillis();
for (int i = 2; i < Length; i++) {
for (int j = 1; j < Length - i; j++) {
if (array[j] > array[j + 1]) {
int c = array[j];
array[j] = array[j + 1];
array[j + 1] = c;
}
}
}
endTime = System.currentTimeMillis();
System.out.println("#### BubbleSort takes " + (endTime - startTime) + "ms");
}
}
class InsertSort extends Thread {
@Override
public void run() {
startTime = System.currentTimeMillis();
for (int i = 1; i < Length; i++) {
int c = array[i];
int j;
for (j = i - 1; j >= 0; j--) {
if (array[j] > c)
array[j + 1] = array[j];
else
break;
}
array[j + 1] = c;
}
endTime = System.currentTimeMillis();
System.out.println("#### InsertSort takes " + (endTime - startTime) + "ms");
}
}
}