• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

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: 2235
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: 508
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 play dumb with me! But you can try this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic