-1

I'm trying to create a simple array of some Worker extends Thread class. I declared a Vector<Worker> then tried to .add(...) elements to it. I keep getting compilation errors. Here is my code:

import java.util.Vector;
public class Main
{
    class Worker extends Thread
    {
        private final int serial;
        Worker(int serial) { this.serial=serial; }
        public void run() { System.out.printf("Worker %d\n",this.serial); }
    }
    static public void main(String argv[]) {
        int i=0; Vector<Worker> workers;
        for (i=0;i<10;i++) { workers.add(new Worker(i)); }
        for (i=0;i<10;i++) { workers[i].start();         }
        for (i=0;i<10;i++) { workers[i].join();          }
    }
}

Here is my compilation line:

$ javac -d . Main.java

And here are my errors:

Main.java:12: error: non-static variable this cannot be referenced from a static context
        for (i=0;i<10;i++) { workers.add(new Worker(i)); }
                                         ^
Main.java:13: error: array required, but Vector<Main.Worker> found
        for (i=0;i<10;i++) { workers[i].start();         }
                                    ^
Main.java:14: error: array required, but Vector<Main.Worker> found
        for (i=0;i<10;i++) { workers[i].join();          }
                                    ^
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 1
    First error comes from the fact, that non-static inner class need a reference to outer class. While inside of static method, there is no `this`. You could declare the inner class as `static` to solve this problem. The second error appears because you declare the variable as a Vector and then try to access it as a regular Array. Vector is not an Array. Use `workers.get(i)` instead. As an extra, `workers` isn't initialized and you will have to handle some exceptions. – Amongalen Jul 20 '20 at 10:09
  • @Amongalen 'Non-static inner' is a tautology. – user207421 Jul 20 '20 at 10:17
  • @MarquisofLorne you can have both static and non-static inner classes, no? – Amongalen Jul 20 '20 at 10:27

1 Answers1

-1

You're calling a non-static class from a static method. Two simple solutions are:

  • Make Worker static
  • Make Worker a separate class

Second, user Workers.get(i) instead of Workers[i].

And last, surround Join method with try & catch or add an exception to the signature.

avivc411
  • 24
  • 5