-1

I'm trying to synchronize a String literal, so that I can control the execution of my threads but for some reason that does not work..

Is there any problem with the way its synchronized?

package scratch1;

public class OrderedThread {
    public static void main(String[] args){
        RunThread first, second, third;
        OrderedThread orderedthread = new OrderedThread();
        first = new RunThread("One",orderedthread);
        second = new RunThread("Two",orderedthread);
        third = new RunThread("Three",orderedthread);
        second.start();
        first.start();
        third.start();
    }

    public void display(String msg){
        synchronized(msg){
            for (int i = 1; i <= 20; i++){
                System.out.println("Name = "+ msg);
            }
        }
    }

}

class RunThread extends Thread{
    String name;
    OrderedThread orderT;
    RunThread(String name, OrderedThread orderT){
        this.name = name;
        this.orderT = orderT;
    }

    public void run(){
        orderT.display(name);
    }
}
user1050619
  • 19,822
  • 85
  • 237
  • 413

1 Answers1

1

The point of synchronization is access to shared resources. Your thread is supposed to acquire the monitor on an object that other threads are trying to access. In your case, each thread acquires a different object's monitor, so none of them blocks.

If instead you passed the literal "One" to your constructors

first = new RunThread("One",orderedthread);
second = new RunThread("One",orderedthread);
third = new RunThread("One",orderedthread);

Then you would see execution in order. Each thread would have to finish its for-loop (inside the synchronized block) before another one can start. This is because each Thread is synchronized on the same String object.

Better yet, use one of them many java.util.concurrent classes that act as locks. For example, Lock.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724