如何从java中的另一个线程类更新和使用main()中的对象
用户不会附加到ArrayList,只打印该线程插入的一个元素。这里需要做什么改变 我尝试过使用同步(用户),但仍然不起作用如何从java中的另一个线程类更新和使用main()中的对象,java,multithreading,arraylist,collections,thread-safety,Java,Multithreading,Arraylist,Collections,Thread Safety,用户不会附加到ArrayList,只打印该线程插入的一个元素。这里需要做什么改变 我尝试过使用同步(用户),但仍然不起作用 /*This is the main Class from which threads are created*/ public class MultiThread { List<String> users = Collections.synchronizedList(new ArrayList<String>()); publi
/*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();
}
}
/*这是创建线程的主类*/
公共类多线程{
List users=Collections.synchronizedList(新的ArrayList());
publicstaticmythread[]线程=newmythread[10];
公共静态void main(字符串[]args)引发IOException{
while(true){
对于(int i=0;i您需要将相同的多线程
对象传递给所有线程。所有线程都在创建多线程
对象的新实例