Note that there are some explanatory texts on larger screens.

plurals
  1. POLearning Java, use of synchronized keyword
    primarykey
    data
    text
    <p>so i was testing with <code>synchronized</code> keyword. Here is an example that I tried: </p> <pre><code>public class MyTest { static int i = 0; public static void main(String[] args) { new Thread(t1).start(); new Thread(t2).start(); } private static void countMe(String name){ i++; System.out.println("Current Counter is: " + i + ", updated by: " + name); } private static Runnable t1 = new Runnable() { public void run() { try{ for(int i=0; i&lt;5; i++){ countMe("t1"); } } catch (Exception e){} } }; private static Runnable t2 = new Runnable() { public void run() { try{ for(int i=0; i&lt;5; i++){ countMe("t2"); } } catch (Exception e){} } }; } </code></pre> <p>When I run it, the output of calling <code>countMe()</code> method from two threads generates this output: </p> <pre><code>Current Counter is: 1 Current Counter is: 2 Current Counter is: 4 Current Counter is: 5 Current Counter is: 6 Current Counter is: 7 Current Counter is: 3 Current Counter is: 8 Current Counter is: 9 Current Counter is: 10 </code></pre> <p>And when I change the method <code>countMe()</code> to: </p> <pre><code>private synchronized static void countMe(){ i++; System.out.println("Current Counter is: " + i); } </code></pre> <p>I get this output: </p> <pre><code>Current Counter is: 1 Current Counter is: 2 Current Counter is: 3 Current Counter is: 4 Current Counter is: 5 Current Counter is: 6 Current Counter is: 7 Current Counter is: 8 Current Counter is: 9 Current Counter is: 10 </code></pre> <p>Although this gives me clear understanding the purpose of <code>synchronized</code>, I want to know is there any other reason as well, that we can use <code>synchronized</code>. Or what I have done here, is the only eason why we need the use of this <code>synchronized</code> keyword? </p> <p>Thanks. </p> <p><strong>EDIT:</strong> Another thing that I am confused with is that in first output why the counter went to 3 after 7. It seems a bit impossible to me, but similar results do happen every time I try, is this normal?</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