• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Peter Rooke
  • Himai Minh
Bartenders:
  • Piet Souris
  • Mikalai Zaikin

Thread run() method

 
Ranch Hand
Posts: 230
IntelliJ IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



Output for 1st case:
MyThread
foo


But the Line 12 code is changed to

Ouput for 2nd case :
MyThread
Bar


What I want to understand is about the 2nd case

 
Bartender
Posts: 2236
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

This is an anonymous class that extends MyThread and overrides its run() method.
When you start this thread the overriden method is executed and it prints "foo".



This is an anonymous class that extends MyThread and does not override its run() method. The run() method is overloaded instead.
When you start this thread the run() method from MyThread is executed and it prints "Bar".
 
Rancher
Posts: 516
15
Notepad Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note that when a thread is started (using thread.start()) its run() method is executed. In the following code:



1st case:

The code on line 12 overrides the MyThread class's run() method. Hence the result: foo
Overrides method: lets say it replaces the code within the method, in this case.


2nd case:

The run() method is not overridden, in this case. Hence the result from the original run method: Bar

Having the line public void run(String s) {  System.out.println("foo"); has no consequence in both cases, in this example.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic