我正在开发一个简单的程序,它将一个包含 10 个元素的整数数组排序到另一个相同长度的数组中。为此,我创建了 10 个线程,每个线程负责从源数组中获取其编号并将其放入新数组中的正确位置。
我有一个实现Runnable的抽象类SortThread。我还有两个扩展上述类的子类,SuperSortThread(初始化源数组,对其编号进行排序并打印出数组)和SimpleSortThread(仅对其编号进行排序)。我试图在“超级线程”初始化数组时锁定源数组。然后,我释放了锁。最后,我有一个创建和启动线程的主类。
这是我的代码:
public abstract class SortThread implements Runnable {
private final int tNumber;
static int[] source = new int[10];
static int[] dest;
public SortThread(int tNumber) {
this.tNumber = tNumber;
}
public final int lessThan() {
/* Calculates the number of elements of source
less than myNumber */
int count = 0;
for (int i = 1; i < 10; i++)
if (source[tNumber] > source[i])
count++;
return count;
}
@Override
public abstract void run();
}
import static java.lang.Thread.sleep;
public class SuperSortThread extends SortThread {
private int tNumber;
public SuperSortThread(int tNumber) {
super(tNumber);
this.tNumber = tNumber;
}
private static void printArray(int[] number) {
System.out.print("\nVector: ");
for (int i = 0; i < 10; i++)
System.out.print(number[i] + " ");
}
@Override
public void run() {
synchronized (source) {
source[0] = 5;
source[1] = 7;
source[2] = 6;
source[3] = 3;
source[4] = 8;
source[5] = 9;
source[6] = 4;
source[7] = 0;
source[8] = 1;
source[9] = 2;
dest = new int[10];
source.notifyAll();
printArray(source);
int myNumber = source[tNumber];
dest[lessThan()] = myNumber;
try {
sleep(1000);
} catch (InterruptedException e) {
System.err.println("Error in Sleep.");
}
printArray(dest);
}
}
}
public class SimpleSortThread extends SortThread {
private int tNumber;
public SimpleSortThread(int tNumber) throws InterruptedException {
super(tNumber);
this.tNumber = tNumber;
}
@Override
public void run() {
synchronized (source) {
try {
source.wait();
} catch (InterruptedException e) {
System.out.println("Wait error in simple thread");
}
int myNumber = source[tNumber];
dest[lessThan()] = myNumber;
}
}
}
出于某种原因,“简单线程”被永久锁定在等待中。会是什么呢?