Prabhat Shankar
Prabhat Shankar

Reputation: 79

Synchronized method implementation and wrong behavior in java

class prab implements Runnable {
    public synchronized void toTest() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(2 * 1000);
            } catch (Exception e) {
                System.out.println("Exception" + e);
            }
            System.out.println("I am from Prab " + i
                    + Thread.currentThread().getName());
        }
    }

    @Override
    public void run() {
        toTest();
    }

}

public class threadClass {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("---");
        Thread t = new Thread(new prab());
        Thread c = new Thread(new prab());
        t.start();
        t.setName("I am T");
        c.start();
        c.setName("I am c");
        System.out.println("From Main thread");
    }
}

Out Put: ---

From Main thread
I am from Prab 0I am T
I am from Prab 0I am c
I am from Prab 1I am c
I am from Prab 1I am T
I am from Prab 2I am c
I am from Prab 2I am T
I am from Prab 3I am T
I am from Prab 3I am c
I am from Prab 4I am T
I am from Prab 4I am c
I am from Prab 5I am T
I am from Prab 5I am c
I am from Prab 6I am T
I am from Prab 6I am c
I am from Prab 7I am T
I am from Prab 7I am c
I am from Prab 8I am c
I am from Prab 8I am T
I am from Prab 9I am T
I am from Prab 9I am c

Expected O/P: first thread T should complete then thread c.

Upvotes: 0

Views: 59

Answers (3)

Scary Wombat
Scary Wombat

Reputation: 44813

synchronized will block on a common object or method. try using static to share or just create one prab obect

Upvotes: 0

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32458

You have synchronized on different objects, since adding synchronized on method signature will lock the current instance. And you have created two object.

Synchronized should be on common object, then only you can see the expected output. Use one prab object for both Threads, then see the output

prab p = new prab();
Thread t = new Thread(p);
Thread c = new Thread(p);

Upvotes: 3

Val
Val

Reputation: 11107

synchronize synchronizes on object instances, not types.

Upvotes: 0

Related Questions