我需要编写一个程序,它有一个整数数组。让我们说阵列的长度是3.首先,它是空的。现在,程序必须使用两个线程,一个将整数写入空数组,另一个将它们删除。我会举个例子:
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个循环)。现在我已经编写了一些代码,但我无法弄清楚如何实现同步对象(整数数组),以便两个线程都可以使用它。下面是代码:
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) {
}
}
答案 0 :(得分:0)
synchronized int putIn(int d) {
if(full == N){
try {
wait();
System.out.println("Array full, thread waits");
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
buffer[idxdeti] = d;
System.out.println("Value " + d + " added");
idxdeti++;
full++;
if (idxdeti == N){
idxdeti = 0;
}
}
return d; //returns the value
}
这是WriteThread的run方法:
public void run() {
System.out.println("WriteThread" + this + "started");
for(int i = 0; i<10; i++){
channel.putIn(i); //puts in a value
}
System.out.println("WriteThread" + this + "ended");
}
现在我只是不知道如何将值返回到takeOut方法,所以当它工作时,它会删除给定的值。