This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronized method Vs synchronized block

 
Anuj Singh
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class TestThread {
public void a() {
System.out.println("Enter in A");
for (int i = 0; i < 10; i++) {
System.out.println("Thread Name " + Thread.currentThread());
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String... args) throws InterruptedException {
TestThread t = new TestThread();
Thread tr = new Thread(new Thre(t), "MyThreads");
tr.start();
System.out.println("Going in Syn block");
t.a();
}
}
class Thre implements Runnable {
TestThread t;
Thre(TestThread t) {
this.t = t;
}
@Override
public void run() {
t.a();
}
It had the output as:


Going in Syn block
Enter in A
Enter in A
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]
Thread Name Thread[MyThreads,5,main]
Thread Name Thread[main,5,main]

Even though we got the lock on t,the main thread is getting executed in parallel with tr.Who owns the lock??How??

 
Jason Irwin
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use code tags, it will make it much easier to read your code.

You don't seem to have any synchronized blocks or methods - that's why.

A quick fix might be to place "synchronized" in the declaration of method a; remember that that will lock on "this" (i.e. the class instance).
If that's not what you want, it would probably be best to wrap the calls to a() in a synchronized block.

What exact method you follow will depend greatly on how you application is meant to behave.
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to threads / synchronization.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic