MultiThreading Synchronized method

thread synchronization in java simple example
multithreading in java
java synchronized static method
static synchronization in java
java synchronized method vs block
java synchronized block
java synchronized object
synchronized block in static method

I have a synchronized method , I created two thread object when I execute the the program. the thread output is not determined. Can any body check and let me know what is wrong with this implementation

package com.karthi.threads;

public class ThreadSyncDemo  extends Thread{


    String name;

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

    public synchronized void wish(){
        for(int i=0;i<5;i++){
            System.out.println("Good morning");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.print(name);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        ThreadSyncDemo th = new ThreadSyncDemo();
        th.name="Test";
        th.start();
        ThreadSyncDemo th1 = new ThreadSyncDemo();
        th1.name="Test1";
        th1.start();

    }

}

output:

Good morning Good morning Test1Good morning TestGood morning Test1Good morning TestGood morning Test1TestGood morning Good morning Test1TestGood morning Good morning TestTest1

Expected output:

Good morning TestGood morning TestGood morning TestGood morning TestGood morning TestGood morning Test1Good morning Test1Good morning Test1Good morning Test1Good morning Test1

You need to take class level lock instead of object level:

synchronized (ThreadSyncDemo.class)
{
   //lock at class level
}

{
public class ThreadSyncDemo extends Thread{
    String name;

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

    public synchronized void wish(){
        synchronized(ThreadSyncDemo.class) {
            for(int i=0;i<5;i++){
                System.out.println("Good morning");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.print(name);
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        ThreadSyncDemo th = new ThreadSyncDemo();
        th.name="Test";
        th.start();
        ThreadSyncDemo th1 = new ThreadSyncDemo();
        th1.name="Test1";
        th1.start();    
    }
}

Method and Block Synchronization in Java, So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time. synchronized block acquires a lock in the object only between parentheses after the synchronized keyword. This means that no other thread can acquire a lock on the locked object until the synchronized block exits. But other threads can access the rest of the code of the method. Which is more preferred - Synchronized method or Synchronized block?

You are locking at the object level.

You have two objects th and th1, they both have separate locks.

What you want is to lock at the class level.

One option is to lock at the class it self.

synchronized (ThreadSyncDemo.class)
{
   //lock at class level
}

Another is to have an explicit lock in the class like this

private final static Object lock = new Object();

And then synchronize on it

synchronized (lock)
{

}

The other method is to use static keyword on the synchronized method or block, because static methods are one per class this locks at the class level. It's not well suited here because of the way you have written this class (In a thread it self).

Synchronized in Java, Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread,� So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time. Java provides a way of creating threads and synchronizing their task by using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword.

You are using two objects. Instead you can create two threads of the same object so that each thread can see other threads lock.

Java Synchronized Blocks, Multithreading and synchronization are a very important topic for any Java programmer. Whenever a thread enters into java synchronized method or blocks it� If one thread is executing the synchronized method, all others thread that invoke synchronized method on the same Object will have to wait until first thread is done with the Object. Example: This shows if more than one threads accessing getLine() method without synchronization.

Synchronized Methods (The Java™ Tutorials > Essential Classes , At times when more than one thread try to access a shared resource, we need to ensure Using Synchronized methods is a way to accomplish synchronization. The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. The more complex of the two, synchronized statements, are described in the next section. This section is about synchronized methods. To make a method synchronized, simply add the synchronized keyword to its declaration:

Java Synchronization Tutorial : What, How and Why?, Java - Thread Synchronization - When we start two or more threads within a program, there may be a situation when multiple threads try to access the same� From "The Java™ Tutorials" on synchronized methods:. First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Synchronization of threads in Java Multithreading, When you run Test t = new Test() jvm create new object on heap and put variable t with link to that object on stack of current thread. When you� Multithreading in Java is a process of executing multiple threads simultaneously.. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

Comments
  • It's because you have two different objects with separate locks. Each thread sees its own lock and can't see the other. In an example like this if you want one common lock you might use a static member: public static synchronized void wish()