Start New Discussion within our Software Development Community
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?

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.

This question has already been answered. Start a new discussion instead.