-1

If I write synchronized(this) in two function of the same java class, but these two functions are maybe called by two threads, does this code still work?

Some fake code maybe looks like:

class A {
        public funA()
            synchronized (this) {
                // do some things here;
            }
        }

        public funB() {
            synchronized (this) {
                // do other things here;
            }
        }
}

Or do I need to add a variable to do it?

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
lucky1928
  • 8,708
  • 10
  • 43
  • 92

2 Answers2

1

What this means is that more than one threads cannot enter these two synchronized blocks (or one of them) at 'the same time'. Whether it works depends on what exactly you want to achieve.

The thread which is currently in such a synchronized block is said to own the object's monitor at that moment of time (in this case the monitor of the object pointed to by this).

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • Actually, it doesn't mean that. Some other thread could synchronize on the instance externally and prevent *any* thread from entering those blocks. – Brian Roach Jan 17 '14 at 21:28
  • 3
    @BrianRoach Actually it means just that. In that case that thread owns the object monitor so 0 threads can enter here (which complies with my statement). I am not commenting here on externally or internally. Each object has exactly one monitor. – peter.petrov Jan 17 '14 at 21:29
  • I may have been confused by your original wording; this is clearer. – Brian Roach Jan 17 '14 at 21:32
1

The threads are synchronized on this. So only one thread is in the class at the same time (assuming there are no other methods). You are not synchronizing on the methods separately. So this might just work ok. Though it is hard to tell as i have no idea what you want to do in the methods. Concurrency is alway tricky.

DukeMe
  • 167
  • 2
  • 8