在我的示例中,我想用 100 到 119 之间的整数填充索引 0 到 19 的 myArray。
我想使用同时运行的两个线程,一个线程将值放入数组中从索引 0 到索引 9 的位置,另一个线程从索引 10 到索引 19 的位置放置值。
当我打印出 myArray 的元素时,我希望看到以下内容:
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
但是因为线程同时运行,两个线程都可以访问我的值,并且我得到了错误的结果,如下:
100 101 102 103 104 105 106 107 108 109 100 101 102 103 104 105 106 107 108 109
我认为问题出在我的 addToArray() 方法上,其中线程访问我的 aNumber 变量。
这是我们需要同步的时候吗?如果是,怎么办?
请查看我的代码:
主类:
public class ThreadMain {
SimpleThread first;
SimpleThread second;
public ThreadMain(String firstName, String secondName) {
first = new SimpleThread(firstName);
second = new SimpleThread(secondName);
}
public static void main(String[] args) {
ThreadMain threadMain = new ThreadMain("FirstThread", "SecondThread");
threadMain.startThreads();
threadMain.waitForThreadsToFinish();
threadMain.displayArrayElements();
}
private void startThreads() {
first.start();
second.start();
}
/**
* main thread sleeps while the other threads are working.
*/
private void waitForThreadsToFinish() {
while (first.isAlive() || second.isAlive()) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void displayArrayElements() {
for (int i = 0; i < 20; ++i) {
int element = SimpleThread.getArrayElement(i);
System.out.println(element);
}
}
}
线程类:
class SimpleThread extends Thread {
private int startIndex;
private int endIndex;
private static int[] myArray = new int[20];
private int aNumber = 100;
public SimpleThread(String str) {
super(str);
}
public void run() {
if (getName().equals("FirstThread")) {
startIndex = 0;
endIndex = 10;
addToArray();//store value of aNumber in myArray from index 0 to index 9.
}
if (getName().equals("SecondThread")) {
startIndex = 10;
endIndex = 20;
addToArray();//store value of aNumber in myArray from index 10 to index 19.
}
}
private void addToArray() {
for (int i = startIndex; i < endIndex; ++i) {
myArray[i] = aNumber;
++aNumber;
}
}
public static int getArrayElement(int index) {
return myArray[index];
}
}
最佳答案
您的问题似乎是 SimpleThread
的两个实例都从起始值 100
开始分配值,并从那里开始。
实现所需结果的一种方法是使用以下内容:
private void addToArray(int startIndex, int endIndex) {
for (int i = startIndex; i < endIndex; ++i) {
myArray[i] = aNumber + startIndex; // Change is here
++aNumber;
}
}
关于java - 如何在Java中使用两个线程将元素存储在一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712285/