import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class A {
private volatile int anInt = 0;
private volatile int jkl = 0;
public static void main(String[] args) {
A a = new A();
Integer[] integers0 = {5,4,7,1,9,3,8,2,0};
List<Integer> integers0s = a.sleepSort(Arrays.asList(integers0));
while (true){
if (a.anInt == integers0.length){
System.err.println("睡眠排序:" + integers0s);
break;
}
}
Integer[] integers1 = {5,4,7,1,-9};
Integer[] integers2 = {5,4,7,1,-9,-3};
Integer[] integers3 = {5,4,7,1,-9,-3,8};
Integer[] integers4 = {5,4,7,1,-9,-3,8,2};
Integer[] integers5 = {5,4,7,1,-9,-3,8,2,3};
List<Integer[]> list = new ArrayList<>();
list.add(integers1);
list.add(integers2);
list.add(integers3);
list.add(integers4);
list.add(integers5);
int i = 1;
for (Integer[] integers : list) {
long start = System.currentTimeMillis();
A aa = new A();
while (true){
List<Integer> bogoSort = a.bogoSort(Arrays.asList(integers));
if (aa.isSort(bogoSort)){
System.err.println(bogoSort);
break;
}
//System.out.println(bogoSort);
}
long end = System.currentTimeMillis();
System.err.println("integers" + i++ + "耗时:" + (end - start) + "毫秒");
}
}
public List<Integer> sleepSort(List<Integer> list) {
List<Integer> result = new ArrayList<>();
for (Integer integer : list) {
new Thread(() -> {
try {
Thread.sleep(integer);
result.add(integer);
anInt++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
return result;
}
public List<Integer> bogoSort(List<Integer> list) {
jkl = 0;
List<Integer> result = new ArrayList<>();
for (Integer integer : list) {
new Thread(()->{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (result){
result.add(integer);
jkl ++;
}
}).start();
}
while (true){
if (jkl == list.size())
return result;
}
}
public boolean isSort(List<Integer> list){
Integer i = list.get(0);
for (Integer integer : list) {
if (integer < i){
return false;
}
i = integer;
}
return true;
}
}
睡眠的精度不知道还有没有什么优化的办法?
原文:https://www.cnblogs.com/bzdofj/p/13806887.html