-2
整数配列を持つプログラムを書く必要があります。配列の長さが3であるとします。まず、空です。さて、プログラムは2つのスレッドを使用しなければなりません。空の配列に整数を書き込み、もう1つはそれらを削除します。私はあなたの例を与える:スレッド、同期、配列のintの埋め込みと削除
thread1 put in value 1 //array has value: 1
thread1 put in value 2 //array has two values: 1 and 2
thread2 deleted value 2 //array now has only one value: 1
thread1 put in value 3 //array has two values: 1 and 3
thread1 put in value 4 //array has three values: 1,3,4
thread1 wants to put value 5 into the array, but it has to wait, because the array is full
thread2 deleted value 4// array has 2 values: 1, 3 and so on........
先生は、それが(例えば、各スレッドは、10サイクルを経る必要があります)指定されたカウンタとのサイクルのために実装することによって、このすべてを行うことが最善かつ最も簡単なことだろう、と述べました。今私はいくつかのコードを書いたが、私はちょうど両方のスレッドが使用できるように同期オブジェクト(整数配列)を実装する方法を理解できません。 HERESにコード:
public class Antras {
public static void main(String[] args) {
System.out.println("Program starts working");
begin();
System.out.println("Program ends work");
}
public static void begin() {
synchronizationObject channel = new synchronizationObject();
try {
Thread putIn = new ReadThread(channel);
putIn.start();
Thread takeOut = new WriteThread(channel);
takeOut.start();
putIn.join();
takeOut.join();
System.out.println("main() ended work");
} catch (InterruptedException exc) {
System.out.println("Error " + exc);
}
}
}
class ReadThread extends Thread {
private synchronizationObject channel;
public ReadThread(synchronizationObject channel) {
this.channel = channel;
}
public void run() {
System.out.println("Thread " + this + "working");
channel.working = false;
System.out.println("Thread " + this + "ends work");
}
}
class WriteThread extends Thread {
private synchronizationObject channel;
public WriteThread(synchronizationObject channel) {
this.channel = channel;
}
public void run() {
System.out.println("Thread " + this + "working");
System.out.println("Thread " + this + "end work");
}
}
class synchronizationObject {
public static int N = 3;
int[] arrayOfInts = new int[N];
synchronized void takeOut() {
}
synchronized void putIn(int d) {
}
}
'WriteThread' /' ReadThread'/'synchronizationObject'には定型文以外のものはありません。これまでに何を試しましたか? –
これを読んで始めてください:http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html –
Re、 "整数配列... [of]長さ3。空です "。空の配列はありません。その実装で配列を使用する上位レベルのデータ構造(たとえば、 'Set'または' List')を記述しようとしているように思えます。私はあなたがより高いレベルのオブジェクトがどのように動作するか、いくつかのテストを書く、テストに合格するオブジェクトのインプリメンテーションを作成する、ということをよりよく理解する必要があると思います。*スレッド安全性新しいスレッドを作成するコードを書くことができます。 –