我的程序需要一個線程數組,它還包含一個由我定義的「隊列」類,它從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類,它需要「Work」對象並進行計算。
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方法。我該怎麼辦?
但我想通過我自己使用wait()和notify() – IAmBlake
是否有任何體面的原因,或者它只是爲了學習目的? – Antoniossss
只能學習目的 – IAmBlake