public class Thread7 implements Runnable {

    public static void main(String r[]) {
        Thread t = new Thread(new Thread7());
        public void run() {


            try {
                    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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.