[英]How to update and use an object in main() from another thread class in java
用戶不會被附加到ArrayList上,而僅打印該線程插入的一個元素。 在此必須進行哪些更改?
我曾嘗試使用synced(users),但仍然無法正常工作。
/*This is the main Class from which threads are created*/
public class MultiThread {
List<String> users = Collections.synchronizedList(new ArrayList<String>());
public static MyThread[] threads=new MyThread[10];
public static void main(String[] args) throws IOException {
while(true){
for(int i=0;i<10;i++){
if(threads[i]==null){
(threads[i] = new MyThread().start();
break;
}
}
}
}
/*Adding names to Arraylist */
public synchronized void adduser(String user){
users.add(user);
}
/*print Array elements */
public void iter(){
Iterator<String> foreach = users.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());
}
}
class MyThread extends Thread {
private BufferedReader in=null;
public void run(){
MultiThread obj=new MultiThread();
in = new BufferedReader(new InputStreamReader());
System.out.println("Enter you name");
name=in.readLine();
obj.adduser(name);
System.out.println("Current Users are:");
obj.iter();
}
}
您需要將相同的MultiThread
對象傳遞給所有線程。 所有線程都在創建MultiThread
對象的新實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.