We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

run() inside main context not allowed?

public class Thread7 implements Runnable {


    public static void main(String r[]) {
        Thread t = new Thread(new Thread7());
        t.start();
        public void run() {
            System.out.println("C");
            System.out.println("D");
            }

        System.out.println("A");

            try {
                    t.join(); 
                    System.out.println("B"); }
            catch(Exception e){}
        }
}

Query1: On compiling this program I get "illegal start of expression" error pointing to public void run. But when I remove that block of code and place it outside main() the program compiles and runs successfully. What is the rule behind it?

Query2: After I place run() outside main() the output is ACDB. What I don't understand is after t.start() is invoked shouldn't the control transfer first to run() block and print CD first then followed by AB?

2
Contributors
1
Reply
7 Hours
Discussion Span
7 Months Ago
Last Updated
2
Views
Question
Answered
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Self-Answered as of 7 Months Ago

The Runnable Interface requires that the class which implements it must over-ride the run() method.And yes,you are declaring a function immediately inside a function which is illegal.Hence run would need to be declared outside main and in the same level as main,i.e. in the class.

t.join() encsures that the daemon threads wait till the main thread is finished.It does not necessarily imply that the run method's statements will be invoked first.

delta_frost
Junior Poster in Training
69 posts since Aug 2009
Reputation Points: 10
Solved Threads: 9
Skill Endorsements: 2

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0599 seconds using 2.75MB