java面试题:已知一个数组[2,4,6,2,1,5],将该数组进行排序(降序,不能用工具类进行排序),创建两条线程交替输出排序后的数组,线程名自定义

时间:2023-03-09 06:10:55
java面试题:已知一个数组[2,4,6,2,1,5],将该数组进行排序(降序,不能用工具类进行排序),创建两条线程交替输出排序后的数组,线程名自定义
package com.swift;

import java.util.Arrays;
import java.util.Comparator; public class ArrayThread_Test { public static void main(String[] args) {
/*
* 已知一个数组[2,4,6,2,1,5],将该数组进行排序(降序,不能用工具类进行排序),创建两条线程交替输出排序后的数组,线程名自定义
*/
Integer[] arr = new Integer[] { 2, 4, 6, 2, 1, 5 };
// 通过数组工具类排序
Arrays.sort(arr, new Comparator<Integer>() { @Override
public int compare(Integer arg0, Integer arg1) {
int num = arg1 - arg0;
return num;
}
});
// 双线快速排序
Integer[] arr2 = new Integer[] { 7, 2, 4, 16, 2, 13, 5 };
kuaisu(arr2, 0, arr2.length - 1);
for (Integer i : arr2) {
System.out.print(i + "~" + "\r\n");
} ArrayThread a = new ArrayThread(arr);
Thread t1 = new Thread(a, "线程1");
Thread t2 = new Thread(a, "线程2"); t1.start();
t2.start(); } private static void kuaisu(Integer[] arr2, int left, int right) { if (left >=right)//当递归到只有一个数时停止
return;
int key = arr2[left];
int i = left;
int j = right;
while (i != j) {
while (arr2[j] > key && i < j) {
j--;
}
while (arr2[i] <= key && i < j) {
i++;
}
if (i < j) {
int temp;
temp=arr2[i];
arr2[i]=arr2[j];
arr2[j]=temp;
}
}
arr2[left]=arr2[i];
arr2[i]=key;
kuaisu(arr2, left, j - 1);
kuaisu(arr2, i + 1, right);
} }

上边是测试类,进行了快速排序 和工具类排序

建立了一个实现Runnable接口的对象,并传递参数

建立两个线程并启动线程

package com.swift;

public class ArrayThread implements Runnable{

    Integer[] arr;
int index=0;
boolean flag=true; public ArrayThread(Integer[] arr) {
this.arr=arr;
} @Override
public void run() {
//for循环在多线程下不适合,虽然是一个对象的内容也会被执行多次循环,因为锁在for循环里边
while (true) {
synchronized (this) {
if(index>=arr.length) {
this.notify();//不唤醒其他线程为什么出不去?虚拟机不停止
break;
}
System.out.println(Thread.currentThread().getName() + " 的输出" + arr[index]);
index++;
if(flag) {
flag=false;
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
flag=true;
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} } }

通过notify唤醒其他线程,通过wait停止自身线程,通过flag标志为交替切换线程