user12456737
user12456737

Reputation:

Multiple threads in on class

I'm trying to create two classes that extends from Thread, I know how to create one class.

public class Main {
  class Thred1 extends Thread {
    public void run() {
      System.out.println("I'm watching a video...");
    }
  }
  
  class Thred2 extends Thread {
    public void run() {
      System.out.println("I'm eating...");
    }
  }
  
  public static void main (String[] args) {
    Thred1 t11 = new Thred1();
    Thred2 t12 = new Thred2();
    t11.start();
    t12.start();
  }
}

And got Main.java:15: error: non-static variable this cannot be referenced from a static context

Is there better way to implement my idea?

Upvotes: 0

Views: 235

Answers (1)

Oussama ZAGHDOUD
Oussama ZAGHDOUD

Reputation: 2159

Your problem is with inner classes and not with threads , try to put all this code in the same file Main.java :

class Thred1 extends Thread {
    public void run() {
        System.out.println("I'm watching a video...");
    }
}
          
class Thred2 extends Thread {
    public void run() {
        System.out.println("I'm eating...");
    }
}

public class Main {
    public static void main (String[] args) {
        Thred1 t11 = new Thred1();
        Thred2 t12 = new Thred2();
        t11.start();
        t12.start();
    }
}

Another possible solution is to use static classes instead of the member inner classes used in your code :

public class Main {
    static class Thred1 extends Thread {
        public void run() {
            System.out.println("I'm watching a video...");
        }
    }

    static class Thred2 extends Thread {
        public void run() {
            System.out.println("I'm eating...");
        }
    }

    public static void main(String[] args) {
        Thred1 t11 = new Thred1();
        Thred2 t12 = new Thred2();
        t11.start();
        t12.start();
    }
}

Or simply you can use Lambda expression , Thread class have a constructor who accept a Runnable as parameter , Runnable is a functional interface so you can pass a Lambda expression as argument like that :

public class Main {
 
    public static void main(String[] args) {
        Thread t11 = new Thread(()->System.out.println("I'm watching a video..."));
        Thread t12 = new Thread(()->System.out.println("I'm eating..."));
        t11.start();
        t12.start();
    }
}

Upvotes: 1

Related Questions