私のプログラムはスレッドの配列をとり、main()から "Work"オブジェクトを取り出してスレッドクラスにプッシュする "Queue"クラスを含んでいます。どのように同じオブジェクトを共有するのを防ぐには?
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];
}
}
ここでは「ワーク」オブジェクトを取得して計算するスレッドクラスです。私が作ったものの
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;
}
}
しかし、「キュー」クラスメソッドは、「キュー」からの私のスレッドアレイを共有し、同じ「仕事」オブジェクトを同期。 1つの配列は、前の配列を適切に実行することなくrunメソッドに入ります。私は何をすべきか?
私はwait()とnotify()を使用して自分自身で処理したい – IAmBlake
それにまともな理由はありますか、それとも学習目的のためですか? – Antoniossss
学習目的のみ – IAmBlake