aspose file tools*
The moose likes Threads and Synchronization and the fly likes Synchronized method Vs synchronized block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Synchronized method Vs synchronized block" Watch "Synchronized method Vs synchronized block" New topic
Author

Synchronized method Vs synchronized block

Anuj Singh
Ranch Hand

Joined: May 04, 2007
Posts: 47
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??


SJCP 1.5 with 93%.Preparing for WCD
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
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.


SCJP6
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

Moving to threads / synchronization.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
 
subject: Synchronized method Vs synchronized block