Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Synchronized and Threads
    primarykey
    data
    text
    <p>I'm having issues with Synchronized not behaving the way i expect, i tried using volatile keyword also:</p> <p>Shared Object:</p> <pre><code>public class ThreadValue { private String caller; private String value; public ThreadValue( String caller, String value ) { this.value = value; this.caller = caller; } public synchronized String getValue() { return this.caller + " " + this.value; } public synchronized void setValue( String caller, String value ) { this.caller = caller; this.value = value; } } </code></pre> <p>Thread 1:</p> <pre><code>class CongoThread implements Runnable { private ThreadValue v; public CongoThread(ThreadValue v) { this.v = v; } public void run() { for (int i = 0; i &lt; 10; i++) { v.setValue( "congo", "cool" ); v.getValue(); } } } </code></pre> <p>Thread 2:</p> <pre><code>class CongoThread implements Runnable { private ThreadValue v; public CongoThread(ThreadValue v) { this.v = v; } public void run() { for (int i = 0; i &lt; 10; i++) { v.setValue( "congo", "lame" ); v.getValue(); } } } </code></pre> <p>Calling Class:</p> <pre><code>class TwoThreadsTest { public static void main (String args[]) { ThreadValue v = new ThreadValue("", ""); Thread congo = new Thread( new CongoThread( v ) ); Thread libya = new Thread( new LibyaThread( v ) ); libya.start(); congo.start(); } } </code></pre> <p>Occasionally i get <code>"In Libya Thread congo cool"</code> which should never happen. I expect only:<br> <code>"In Libya Thread libya awesome"</code><br> <code>"In Congo Thread congo cool"</code></p> <p>I dont expect them to be mixed.</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.
 

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