Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>I can compile it just fine, but when I run the program, this is what I get ...</p> </blockquote> <p>There are a couple of things wrong with your program:</p> <ol> <li><p>The main thread is not waiting for the <code>Counter</code> threads to finish before it prints out the totals. If you need to wait for a thread to complete then you call <code>thread.join()</code> on it.</p> <pre><code>Thread counter1 = new Thread(new Counter1(c)); counter1.start(); // start other threads here... // now wait for the counter1 to finish counter1.join(); </code></pre> <p>In your case, the 3 <code>Counter</code>s are forked but the main only sleeps a bit and then quits. The <code>Counter</code> threads are still running.</p></li> <li><p>Each of the <code>Counter</code> threads is adding values to fields inside the <code>Cinema</code> but there is no synchronization in <code>Cinema</code>. Anytime two threads are modifying the same field, there must be some mutex protection and memory synchronization.</p> <p>The easy thing to do here is to make the <code>Cinema.reservation(...)</code> method be <code>synchronized</code>. Then each of the <code>Counter</code> objects will get a lock on the <code>Cinema</code> instance which will ensure only one <code>Counter</code> updates the <code>Cinema</code> at one time. The <code>synchronized</code> keyword also ensures that the fields in the <code>Cinema</code> object are memory synchronized as well.</p> <pre><code>synchronized void reservation(int n,int p) { ... </code></pre></li> <li><p>As always, you should consider using the <code>ExecutorService</code> classes instead of forking threads yourself. See the <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/exinter.html" rel="noreferrer">Java tutorial</a>.</p></li> </ol>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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