Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从java中的另一个线程类更新和使用main()中的对象_Java_Multithreading_Arraylist_Collections_Thread Safety - Fatal编程技术网

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

如何从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

用户不会附加到ArrayList,只打印该线程插入的一个元素。这里需要做什么改变

我尝试过使用同步(用户),但仍然不起作用

/*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您需要将相同的
多线程
对象传递给所有线程。所有线程都在创建
多线程
对象的新实例