zoukankan      html  css  js  c++  java
  • 睡眠排序

    原理是构造 n 个线程,它们和这 n 个数一一对应。初始化后,线程们开始睡眠,等到对应的数那么多个时间单位后各自醒来,然后输出它对应的数。这样最小的数对应的线程最早醒来,这个数最早被输出。等所有线程都醒来,排序就结束了。 放个例子:

    public class SleepSort {
        public static void main(String[] args){
            int[] nums={9,7,2,6,15,8,9,9,9,9,9};
            SleepSort.sort(nums);
            for(int n:nums)
                System.out.printf("%d    ",n);
        }
    
        public static void sort(int[] nums){
            Sleeper.idx=0;
            Sleeper.output=new int[nums.length];
            for(int i=0;i<nums.length;i++)        //[1]
                new Sleeper(nums[i]).start();
    
            try {
                Thread.sleep(100);                  //[2]
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for(int i=0;i<nums.length;i++)
                nums[i]=Sleeper.output[i];
        }
    }
    
    class Sleeper extends Thread{
        public static int[] output;
        public static int idx;
    
        private int sleep_time;
    
        public Sleeper(){
            this.sleep_time=0;
        }
        public Sleeper(int sleep_time){
            this.sleep_time=sleep_time;
        }
        @Override
        public void run(){
            try{
                Thread.sleep(this.sleep_time);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            output[idx++]=this.sleep_time;
        }
    }
  • 相关阅读:
    java中Excel导出
    springmvc接收各种参数
    restTemplate使用
    java中io流的操作
    在线Cron表达式生成器
    springBoot实现socketio
    maven的使用
    idea中导入githup项目
    java 单例模式之线程安全的饿汉模式和懒汉模式
    spring定时任务的集中实现
  • 原文地址:https://www.cnblogs.com/hao66/p/8651850.html
Copyright © 2011-2022 走看看