I am interested in such a question: there is a stream in it, a certain collection, there are several streams that perform certain actions, it is necessary to add data to the collection from the streams, while the streams will not have the TERMINATED state while the program is running. link to the collection?

class classname static Map map; class job1 thread1-> { .... classname.map.add(...)....} class job1 thread2-> { .... classname.map.add(...)....} 

    2 answers 2

    You can have a static link to the map instance, or you can pass the map instance directly to the task in the thread. But I would avoid static variables without real need.

    In this case it is much more important that access to the map should be synchronized either in the critical section within the executable task (it is important to synchronize on the same monitor), or at the expense of a properly chosen map implementation (for example, ConcurrentHashMap).

    The specific approach depends on the execution logic in the threads.

    • Another question: is it necessary to block a collection during the integration of elements? Logically, if the collection is changed by another thread, does an error wake up or not? - e_klimin
    • In general, when it comes to modifying shared data, access should always be synchronized. In the specific case, much depends on the logic and the specific implementation. - a_gura

    It is better to use queue in multi-threaded applications. Private BlockingQueue <String> queue = new LinkedBlockingQueue <String> ();

    You will pass a reference to the object to the stream, the object queue.remove () or queue.poll () is read - both methods remove the String element test = queue.poll () from the queue; // turn to decrease.

    What would neblo colises when simultaneously accessing the queue of multiple threads must be synchronized (queue) {perform actions here}

    during synchronization, only one stream can read at a time.

    • What do you mean better? Better for what? Queue and collection of other types of tools that are suitable for specific cases. None of them is better or worse. - a_gura
    • I solved this problem by copying to a local collection; in my case, blocking is not quite suitable because the iterator may not finish soon. - e_klimin