3

I'm trying to teach myself threads but can't seem to get synchronized() to work. This is what I'm doing:

In a class Test I'm declaring a variable

static String toggy = "false"; 

Then a runnable (MyRunnable) with this run method:

@Override
public void run() {
    synchronized (toggy) {
        System.out.println("toggy for " + name + " BEFORE = " + toggy);
        int b = 0;
        for(int i=0; i<1000; i++) {
            b++;
        }
        System.out.println("toggy for " + name + " AFTER = " + toggy);
        System.out.println("--------------------------------------------\n");

        if(toggy.equals("false")) {
            toggy = "true";
        } else if(toggy.equals("true")) {
            toggy = "false";
        }                                       
    }
}

I'm testing this here:

for (int i = 0; i < 90; i++) {
    Runnable task = new Test.MyRunnable(i+"");
    Thread worker = new Thread(task);
    worker.setName(String.valueOf(i));
    // Start the thread, never call method run() direct
    worker.start();
}                           

From what I understand, the synchronized block should prevent the value of "toggy" from changing while a certain thread is running. But when I run the program every now and then it does. What am I missing?

Jonathan
  • 20,053
  • 6
  • 63
  • 70
Eddy
  • 3,533
  • 13
  • 59
  • 89

1 Answers1

4

By assigning different values (String instances) to toggy, the synchronized block is locking different objects:

synchronized ("false")
{
}

or:

synchronized ("true")
{
}

This will allow multiple threads to enter the block code that the synchronized is meant to protect. Use a different object for locking:

static final Object lock = new Object();

synchronized (lock)
{
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Thanks hmjd. I think I understand the issue with the different values of "toggy". But why synchronizing on "lock" does the trick? So, I can just synchronize on any object who's value doesn't change? When is it right to synchronized on an object with a meaningful value? – Eddy Nov 09 '12 at 14:19
  • More discussion on this here http://stackoverflow.com/questions/3369287/synchronized-block-lock-object-question – Eddy Nov 09 '12 at 14:50