Note that there are some explanatory texts on larger screens.

plurals
  1. POjava thread synchronization issue
    text
    copied!<p>Would like to post some doubts regarding Thread synchronization. I understood the concepts of synchronization. But when I implemented a sample java program through multithreading, I could not achieve the result what I want. But finally I could achieve the result by changing one line of code.But I would like to know whats wrong with the below code.</p> <p>Here when I use synchronized block, synchnonized(SharedResource.class) I could achieve the result what I want. why it is not working for synchonized method and synchronized(this) block?</p> <pre><code>public class SharedResource { public synchronized void access(String name){ System.out.println(name+" :accessed shared resoure"); System.out.println(name+" doing his job: "); for(int i = 0; i &lt; 5;i++){ try { System.out.println(name+": "+ i); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(name+" :finished doing his job.."); } } public class SharedAccessThread implements Runnable { private String name ; public SharedAccessThread(String name) { this.name = name ; } @Override public void run() { SharedResource resource = new SharedResource(); resource.access(Thread.currentThread().getName()); } } public class MultiThreading { public static void main(String[] args) { SharedAccessThread thread = new SharedAccessThread(Thread.currentThread().getName()); Thread t1 = new Thread(thread); t1.setName("A"); Thread t2 = new Thread(thread); t2.setName("b"); Thread t3 = new Thread(thread); t3.setName("C"); t1.start(); t2.start(); t3.start(); } } The expected out put is below: A :accessed shared resoure A doing his job: A: 0 A: 1 A: 2 A: 3 A: 4 A :finished doing his job.. C :accessed shared resoure C doing his job: C: 0 C: 1 C: 2 C: 3 C: 4 C :finished doing his job.. b :accessed shared resoure b doing his job: b: 0 b: 1 b: 2 b: 3 b: 4 b :finished doing his job.. </code></pre> <p>But it gives in a shuffled manner. That means A accessed shared resource..B doing his job...,etc which I dont want.</p>
 

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