代码如下
public class SellpSort {
public static void main(String[] args){
int[] ints = {1,3,5,6,8,22,11,0,99};
SortThread[] sortThreads = new SortThread[ints.length];
for (int i = 0; i < sortThreads.length; i++){
sortThreads[i] = new SortThread(ints[i]);
}
for (int i = 0; i < sortThreads.length; i++){
sortThreads[i].start();
}
}
}
class SortThread extends Thread{
int ms = 0;
public SortThread(int ms){
this.ms = ms;
}
public void run(){
try{
sleep(ms*10+10);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(ms);
}
}
执行效果
算法原理
它原理是构造n个线程,它们和这n个数一一对应。
初始化后,线程们开始睡眠,等到对应的数那么多个时间单位后各自醒来,然后输出它对应的数。
这样最小的数对应的线程最早醒来,这个数最早被输出。
等所有线程都醒来,排序就结束了。