我需要运行一个名为的 java 程序ArrayHolder
,它将运行两个Threads
. ArrayHolder
会有一个Array
. ThreadSeven
将Array
用 7 和ThreadOne
1 覆盖其中的每个元素。执行后的结果应该是 7,1,7,1,7,1,7,1 等。我已经解决了这个问题,虽然我不喜欢我的解决方案并且是希望你能提出更好的方法。
ps:两个线程都必须写入所有索引。
public class ArrayHolder {
private int[] array = {1, 2, 3, 4, 5, 6, 4, 8, 9, 10};
public void writeInt(int pos, int num) {
array[pos] = num;
}
public static void main(String[] args) {
ArrayHolder holder = new ArrayHolder();
ThreadSeven seven = new ThreadSeven(holder, null);
Runnable one = new ThreadOne(holder, seven);
Thread thread1 = new Thread(seven);
Thread thread2 = new Thread(one);
seven.setThread(one);
thread1.start();
thread2.start();
holder.printArray();
}
private void printArray() {
for (int i = 0; i < 10; i++) {
System.out.println(array[i]);
}
}
public class ThreadSeven implements Runnable {
private ArrayHolder array;
private Runnable t;
private int flag=0;
@Override
public void run() {
for(int i=0;i<10;i++){
array.writeInt(i, 7);
flag=(flag+1)%2;
if (flag==0){
synchronized(t){
t.notify();
}
}else{
synchronized(this){
try {
this.wait();
} catch (InterruptedException ex) {
Logger.getLogger(ThreadSeven.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
public ThreadSeven (ArrayHolder ar,Runnable t){
array=ar;
this.t=t;
}
public void setThread(Runnable t){
this.t=t;
}
}
public class ThreadOne implements Runnable {
private ArrayHolder array;
private Runnable t;
private int flag = 0;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
array.writeInt(i, 1);
flag = (flag + 1) % 2;
if (flag == 1) {
synchronized (t) {
t.notify();
}
} else {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException ex) {
Logger.getLogger(ThreadSeven.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
public ThreadOne(ArrayHolder ar, Runnable t) {
array = ar;
this.t = t;
}
public void setThread(Runnable t) {
this.t = t;
}
}