tural
tural

Reputation: 320

How threads work

I have a problem understanding how threads work:

class ThreadTest implements Runnable{ 
    synchronized void methodA(long n){ 
        for (int i=1;i<3;i++){System.out.print(n+" "+i)} 
    } 

    public void run(){ 
        methodA(Thread.currentThread.getId()); 
    } 

    public static void main(String ... args){ 
        new Thread(new ThreadTest()).start(); 
        new Thread(new ThreadTest()).start(); 
    } 
} 

As I currently understand, because methodA is a synchronized for loop in this method, it must finish before next thread calls this method -- so the result must be like 4-1 4-2 5-1 5-2...

Is it possible to have a result like 4-1 5-1 5-2 4-2? If yes, how?

Upvotes: 3

Views: 156

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200296

Is it possible to have result like 4-1 5-1 5-2 4-2.?

It is possible.

If yes how?

You are using the this reference as the object which is locked by synchronized. Since you've got two distinct instances of ThreadTest, each method locks its own instance and mutual exclusion is not achieved.

So, what you must understand is the semantics of synchronized: there is always a clearly defined object involved whose monitor is acquired. Basically, that object notes which thread has acquired its monitor and will allow only the same thread to re-acquire it; other threads will be put on hold until the monitor is released. Any other object, naturally, has nothing to do with this and its monitor is free to be acquired by any thread.

A synchronized method implicitly uses this for the lock. What you can do for your example is declare a static final Object lock = new Object(); and use synchronized(lock) in your method.

Upvotes: 13

Sanjaya Liyanage
Sanjaya Liyanage

Reputation: 4746

you can have results 4-1 5-1 5-2 4-2 .Also you may get 5-1 5-2 4-1 4-2 as result since you can not guarantee which thread will run.Thread start will only put that thread in runnable list.Thread scheduler will decide which thread to run

Upvotes: 1

Related Questions