基本思想:根据CPU的调度算法实现,对一组数据进行排序,不能存在负数值。

这个数是多大,那么就在线程里睡眠它的10倍再加10。

不是睡眠和它的数值一样大的原因是,当数值太小时,误差太大,睡眠的时间不比输出的时间少,那么就会存在不正确的输出结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class SleepSort {

public static void main(String[] args) {

int[] arr = {1,4,7,3,8,9,2,6,5};
//创建指定长度的线程数组
SortThread[] sortThreads = new SortThread[arr.length];
//指定每个线程数组的值
for (int i = 0; i < sortThreads.length; i++) {
sortThreads[i] = new SortThread(arr[i]);
}
//开启每个线程
for (int i = 0; i < sortThreads.length; i++) {
sortThreads[i].start();
}
}
}
class SortThread extends Thread{
int s = 0;
public SortThread(int s){
this.s = s;
}
public void run(){
try {
sleep(s*10+10); //睡眠指定的时间
} catch (InterruptedException e) {
e.printStackTrace();
}
//输出该数
System.out.println(s);
}
}