如何从java中的另一个线程类更新和使用main()中的对象

时间:2017-06-08 22:50:32

标签: java multithreading arraylist collections thread-safety

用户没有被附加到ArrayList,只打印一个由该线程插入的元素。这里需要做些什么改变?

我尝试过使用synchronized(用户),但仍无法使用。

/*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();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要将相同的MultiThread对象传递给所有线程。所有线程都在创建MultiThread个对象的新实例。