Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do you return one instance of a variable that has been edited in 4 different Threads?
    primarykey
    data
    text
    <p>OKAY, I'm sorry for the Title. I really didn't know how to phrase this. I'll try better here.</p> <p>So, I have 2 Java classes. We'll call them <strong>FirstClass</strong> and <strong>SecondClass</strong> (which implemts Runnable). In <strong>FirstClass</strong>, I'm doing some stuff and then I'm creating 4 threads. </p> <pre><code>Thread t1 = new Thread (new SecondClass(s1)); Thread t2 = new Thread (new SecondClass(s2)); Thread t3 = new Thread (new SecondClass(s3)); Thread t4 = new Thread (new SecondClass(s4)); </code></pre> <p><strong>s1</strong>, <strong>s2</strong>, <strong>s3</strong> and <strong>s4</strong> are all of type <em>String</em> and hold individual values.</p> <p>Then I start the threads straight away. </p> <pre><code>t1.start(); t2.start(); t3.start(); t4.start(); </code></pre> <p>Then in my <strong>SecondClass</strong>, I am taking these strings in the default constructor as follows</p> <pre><code>HashMap&lt;String, Integer&gt; map; public SearchResults(String s) { map.put(s, 0); } </code></pre> <p>in the run() method I am doing the following</p> <pre><code>public void run() { try { System.out.println(map); } catch (Exception e) { // TODO: handle exception } } </code></pre> <p>So the result of this useless program is that <strong>map</strong> is printed out 4 times with 4 different values. </p> <p>I am wondering how I can return one instance of <strong>map</strong> that has all the values that <strong>t1</strong> put into it and all the values that <strong>t2</strong> put into it etc etc. They are all working off the same variable, <strong>map</strong>, but each Thread does it's own thing it seems. </p> <p>Could I maybe, let the threads execute and then when they are all finished, return the <strong>map</strong> to another class or something? I really don't know much about Threads so this has been confusing me. Any help would be greatly appreciated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload