之前看到一个搞笑的排序,把待排序数组中的元素放进独立的线程中睡眠,谁的线程先醒来谁就是最小值,反之是最大值。闲来无事用go实现一下
package main
import (
"fmt"
"time"
)
func main() {
l := []int{1,2,10,3,8,5,3,4}
result := make(chan int)
for _,i := range l{
go sleepHandler(i,result)
}
data := make([]int,0,len(l))
for {
if len(data) >= len(l) {
fmt.Printf("都处理完了, 关闭channel")
close(result)
}
cur,ok := <- result
fmt.Println(ok)
if !ok {
break
}
data = append(data,cur)
fmt.Printf("-> %v \n\n",data)
}
fmt.Println("done")
}
func sleepHandler(i int, r chan int) {
time.Sleep(time.Duration(i) *time.Second)
r <- i
}