我的程序采用一个线程数组,它还包含一个由我定义的“Queue”类,它从main()获取“Work”对象并将它们推送到线程类中。
class Queue {
volatile boolean value = false;
int i;
Work[] WI;
public Queue(int num) {
this.WI = new Work[num];
this.i = 0;
}
synchronized void enqueue(Work WI) {
if (value) {
try {
wait();} catch (Exception e) {
System.out.println(e);
}
}
this.WI[i++] = WI;
value = true;
notify();
}
synchronized Work dequeue() {
if (!value) {
try {
wait();} catch (Exception e) {
System.out.println(e);
}
}
value = false;
notify();
return this.WI[i - 1];
}
}
这是我的Thread类,它需要“工作”对象并计算。
class Thread_Produce implements Runnable {
Work WI;
Queue q;
int row, column,n,s, start;
Thread t;
public Thread_Produce(Queue q,int n) {
this.q = q;
t = new Thread(this);
this.n = n;
this.s = 0;
this.start = 0;
t.start();
}
public void run() {
for (int j = 0; j < n; j++) {
this.WI = (Work) q.dequeue();
for (int i = 0; i < WI.array1[0].length; i++) {
s = s + WI.array1[WI.row][i] * WI.array2[WI.column][i];
}
System.out.println(s);
s = 0;
}
}
但是,虽然我使“队列”类方法同步,但我的线程数组与“队列”共享相同的“工作”对象。一个数组进入run方法而没有正确执行前一个方法。我该怎么办?