• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads and Inner Classes

David Harrigan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say one has an inner class defined thus:-

Then will that object lock be on object B or object A or both?

[This message has been edited by David Harrigan (edited December 14, 2000).]
Jerry Pulley
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The lock will be that of the inner object only. Even though an inner class cannot be instantiated without an enclosing instance, the outer and inner instances are separate objects. They each have their own lock, and their locks are not associated.
With that said, I note that your example will not compile. Class A implements Runnable, but does not define run(), and so must be made abstract. Further, you cannot construct a Thread by passing an instance of A.B to its constructor - B is not a Runnable.
Rahul Mahindrakar
Ranch Hand
Posts: 1869
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the code below

This is the output
---------- java ----------
in the outer class 0
in the inner class 0
in the inner class 1
in the inner class 2
in the inner class 3
in the inner class 4
in the inner class 5
in the inner class 6
in the inner class 7
in the inner class 8
in the inner class 9
in the outer class 1
in the outer class 2
in the outer class 3
in the outer class 4
in the outer class 5
in the outer class 6
in the outer class 7
in the outer class 8
in the outer class 9
in the outer class 10
in the outer class 11
in the outer class 12
in the outer class 13
in the outer class 14
in the outer class 15
in the outer class 16
in the outer class 17
in the outer class 18
in the outer class 19
Hello World!
in the inner class 10
in the inner class 11
in the inner class 12
in the inner class 13
in the inner class 14
in the inner class 15
in the inner class 16
in the inner class 17
in the inner class 18
in the inner class 19
Normal Termination
Output completed (6 sec consumed).

the program above creates two threads that are contending to print out a line of code on the console one from the outerclass and one from the innert class.
The methods main(of innert) and xyz(outerclass) are synchronized. A thread accesses the innert class which is an inner class and sleeps in between. Since sleep does not give up the lock the outer class should not be able to do its work if there is only one lock associated with both an inner and outer class. since this is not true, the outerclass is able to do its work in between.

Rahul P. Mahindrakar
my overalls have superpowers - they repel people who think fashion is important. Tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!