我有一个简单的循环在字符串数组,然后将字符串传递给threadlist方法。不过,我似乎无法打印出两个字符串。它只是打印第二个名字"Fred"
,这使我认为我用第二个字符串覆盖了第一个字符串。我如何使ArrayList
包括字符串"Tim"
和"Fred"
?循环线程arraylist
import java.util.ArrayList;
public class Threads extends Thread implements Runnable{
private ArrayList threadList;
private String e;
public static void main(String[] args) {
String[] elements = {"Tim","Fred"};
Threads t = new Threads();
for (String e: elements) {
t.threadL(e);
}
//loop over the elements of the String array and on each loop pass the String to threadL
for (int index = 0;index<t.threadList.size();index++){
System.out.print(t.threadList.get(index));
}
//loop over the threadList arraylist and printout
}
public ArrayList<String> threadL(String e) {
threadList = new ArrayList<>();
threadList.add(e);
return(threadList);
}
}
'threadList = new ArrayList <>();'你在这里发生了什么?特别是当你第二次调用'threadL'时? – Tom
你在哪里实现Runnable? – Untitled123
每次调用'threadL'时,您都在创建一个新的'ArrayList'。 –