Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>@Kaddy, you have two problems with the code you posted:</p> <ol> <li>You have multiple instances of UI, and</li> <li>Your locking is per-method, but it appears you want to lock across methods.</li> </ol> <p>Let me explain both. First, a really quick explanation of <code>synchronized</code>. Consider this code:</p> <pre><code>class MyClass { synchronized void myMethod() { // do something } } </code></pre> <p>This is essentially shorthand for:</p> <pre><code>class MyClass { void myMethod() { synchronized (this) { // do something } } } </code></pre> <p>How <code>synchronized</code> works is that if multiple threads try to sync on the same <strong>instance</strong>, then only one is allow inside the sync block at a time. When thread that did go inside leaves the block -- either through regular execution or because of exception -- then one of the remaining threads is allowed to enter its sync block. This goes on until no threads are trying to acquire a lock on that instance.</p> <p>So to your first problem: each thread has its own instance of Ui. So the threads are sync'ing on <em>different instances</em>. You can fix that problem in two ways.</p> <p>Either share one instance of Ui:</p> <pre><code>UI ui = new UI(); RunnableUI rm1 = new RunnableUI(ui); RunnableUI rm2 = new RunnableUI(ui); </code></pre> <p>Or lock on something other than the UI instance:</p> <pre><code>class UI { private static final Object LOCK = new Object(); public Object getLock() { return LOCK; } public void update() { synchronized (getLock()) { // do something } } ... } </code></pre> <p>To your second problem. You are not locking broadly enough. If you opt for a shared UI instance, try this:</p> <pre><code>class RunnableUI implements Runnable { private final UI _ui; RunnableUI(UI ui) { _ui = ui; } public void run() { synchronized (_ui) { _ui.update(20); _ui.stop(); } } } </code></pre> <p>If you opt for a shared lock, try this:</p> <pre><code>class RunnableUI implements Runnable { public void run() { UI ui = new UI(); synchronized (ui.getLock()) { ui.update(20); ui.stop(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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. 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