简体   繁体   中英

Unable to create an object of class which implements Runnable interface

I am trying to create an object of a class which implements Runnable interface in the main method and passing those objects to the thread pools. But the IDE shows error which reads non-static variable this cannot be referenced from a static context ie, I couldn't create the objects in the first place. I couldn't figure out what is exactly wrong with this code. Everything else works fine, but just this line of code is showing compile error. Can anyone help??

package threads;

import java.util.concurrent.*;

public class Tut5 {

    public static void main(String[] args) {

        ExecutorService exe = Executors.newFixedThreadPool(2);

        for(int i=0; i<5; i++) {
            Runner5 r5 = new Runner5(i);
            exe.submit(r5);
        }

        exe.shutdown();

        System.out.println("All tasks submitted.");

        try {
            exe.awaitTermination(1, TimeUnit.DAYS);
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("All tasks completed.");
    }

    class Runner5 implements Runnable {

        private int id;

        public Runner5(int id) {
            this.id = id;
        }

        public void run() {

            System.out.println("Starting thread: " + id);

            try{
                Thread.sleep(3000);
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("Ending thread: " + id);
        }
    }
}

There u go @jtahlborn

  • non-static variable this cannot be referenced from a static context -

this error comes when you are using not static instance or method in static method or block.

And main method is static public static void main(String[] args) so its simple it will populate error.

Here your class Runner5 implements Runnable class is inner class which you are accessing in static main method so it generate -

No enclosing instance of type Tut5 is accessible.
Must qualify the allocation with an enclosing instance of type Tut5
(e.g. x.new A() where x is an instance of Tut5).

you can define this inner class out of your Tut5 class or mark this Runner5 as static. or create an instance of Tut5 class and create a method and place your rest of the code.

Thanks

As others have answered, the Runner5 class is an inner class of Tut5 . As such, it needs an outer instance to be instantiated.

It you make Runner5 a static class, it becomes a static nested class which does not need an outer instance.

static class Runner5 implements Runnable {
...
}

But, as others have noted, you should put the class in its own class file, unless you are working on an exercise on nested classes, or you are sure the class is only useful in combination with the class Tut5, and will only be referenced from that class.

Seee http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html for some insight.

The problem here is that you have unintentionally created an inner class. It seems that you are a beginner with Java, and as inner classes are a fairly-advanced feature of Java, I think you would be best off avoiding them for the time being.

Until you get more confident with Java, I would recommend that you put each of your classes into a separate file. Move the code for your Runner5 class into a separate file, make the class public and name it Runner5.java . You should then find that your code compiles fine.

As it stands, your code defines a class Runner5 that belongs to each instance of Tut5 you create. But you never create any instances of Tut5 , so you can't create any Runner5 s that belong to them. If you added the static modifier to your Runner5 class, then your inner class Runner5 would belong to the Tut5 class instead of instances of this class. You would then be able to create Runner5 s from within your main method. However, as you're still learning Java, I'd recommend keeping things simple and sticking to the one-class-per-file rule for the moment.

The simplest solution, just copy the Runner5 class to its own file.

Unless you have a very good reason, I don't see why you have to use nested classes for this case, it doesn't change anything (in the code you showed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM