0

I am writing a Multi threaded program to print numbers from 1 to n.

I have 2 threads which has a runner which prints Odd number. And 1 thread which has a runner which prints Even number.

while (true) {              
            synchronized (ng) {                 
                while (ng.getData() % 2 == 1) {
                    try {
                        ng.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                ng.increment();
                ng.notify();
}

I have put debug points inside synchronized method. Attaching the snapshot:

enter image description here After the 1st thread called notify(), in the debug tab, it still shows

owns NumberGenerator

You can see in the snapshot:

It says 2 threads: Thread-1 and Thread-2 owns NumberGenerator object.

How can 2 threads hold a lock on object at same time?

Nicky
  • 1,025
  • 3
  • 15
  • 29
  • If you want to print the numbers 1 to n in sequence, **don't** use multiple threads to do it! – Elliott Frisch Feb 26 '18 at 02:34
  • You mean I should use `for loop` ,right? – Nicky Feb 26 '18 at 02:35
  • or maybe you can use parallel stream :) – HuntsMan Feb 26 '18 at 02:35
  • I mean it is the very definition of a sequential task, there is no gain to be had in making a parallel application behave sequentially - and there is a cost to running the parallel jobs. This is a direct consequence of Amdahl's Law. – Elliott Frisch Feb 26 '18 at 02:38
  • Not overly familiar with this since there are so many good libraries protecting us from having to write this sort of code ourselves, but.. aren't you supposed to `notify()` from inside the `synchronized` block? All the examples that I can find use that pattern, but you've got `notify()` outside the `synchronized` block. Could that be causing the issue? – Paul Hicks Feb 26 '18 at 02:57

1 Answers1

2

It is not possible for two threads to hold the same lock at the same time. This could be due to the two threads exchanging the lock in between their data being displayed in the debugger. So, for example, the debugger would acquire the data for thread 1, then thread 1 releases the lock, which is then acquired by thread 2, where the debugger then acquires the data for thread 2. This would make it appear that both threads have the lock at the same time. The answer to this question explains it well: Multiple threads hold the same lock?.

But I do agree with Elliot, if you just want to print the number 1 to n, a for loop is the way to go. But if you want to learn how threads work, having two threads could be a good exercise

  • 1
    This looks like an exercise in learning `synchronized`, `notify()` and `wait()`. Doing it the right way may be less important than doing it the educational way :) – Paul Hicks Feb 26 '18 at 02:59