KaranDwivedi
KaranDwivedi

Reputation: 1

How to create Threads in main()

I have a very simple program with a Threads. Suppose I want that the thread starts after some code (i.e. in the middle of program). How do I achieve this?

When I try to start the thread in main() after the code(code given below), it shows the error: non-static variable this cannot be referenced from a static context.

public class Main {

    public class MyThread implements Runnable {

       public void run() {
        //do something
       }
    }

    Thread t1 = new Thread (new MyThread());

    public static void main(String[] args) {
        // some code
        t1.start();
        //some code
    }
}

Can anybody plese tell me how to correct the error.

Thanks in advance for help.

Upvotes: 0

Views: 94

Answers (2)

Greg Reynolds
Greg Reynolds

Reputation: 10186

I think you want to instantiate your thread from within the main function, as it is a static function.

 public class Main {

 public class MyThread implements Runnable {

    public void run() {
     //do something
    }
 }
     public static void main(String[] args) {
         Thread t1 = new Thread (new MyThread());

         // some code
         t1.start();
         //some code

     }
 }

Upvotes: 4

Joachim Sauer
Joachim Sauer

Reputation: 308031

If you don't need access to the Thread variable outside of your main, then the correct solution would be to simply use a local variable:

public static void main(String[] args) {
     // some code
     Thread t1 = new Thread (new MyThread());
     t1.start();
     //some code
}

Otherwise, you'd either need to make t1 static or let your code run inside a non-static method (i.e. create an instance of your main class and do your actual work in a method that you call from main).

Upvotes: 4

Related Questions