这题我会,来看看【睡眠排序】:
import java.util.ArrayList;
import java.util.List;
public class SleepSort {
public static void sleepSort(int[] array) {
List<Thread> threads = new ArrayList<>();
for (int num : array) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(num);
System.out.print(num + " ");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threads.add(thread);
thread.start();
}
// 等待所有线程完成
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6};
System.out.println("排序前:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println("\n排序后:");
sleepSort(numbers);
}
}
这题我会,来看看【睡眠排序】:
import java.util.ArrayList;
import java.util.List;
public class SleepSort {
public static void sleepSort(int[] array) {
List<Thread> threads = new ArrayList<>();
for (int num : array) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(num);
System.out.print(num + " ");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threads.add(thread);
thread.start();
}
// 等待所有线程完成
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6};
System.out.println("排序前:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println("\n排序后:");
sleepSort(numbers);
}
}