Search code examples
javamultithreadingclasssharing

Multiple classes running on same Thread in Java


I have a class, let's call it "Class1", which implements Runnable, and starts a thread, named "thread 1", using thread.start();

I have another class which is a subclass of Class1, called "Class2". It contains the main method, and runs another method in the class which executes a while loop. What I've noticed however, is that the Thread that executes the while loop in Class2 isn't "thread 1", but an entirely different thread.

Is there a way I can make the Class2 while loop execute on "thread 1" instead of its own thread? If I'm being too vague let me know. :) And thanks for any help.


Solution

  • There are a couple problems I see in your description of your code:

    • You should separate out your main class and not have it be in the subclass Class2. Call it Main to not be confused.
    • You should never start a thread in an object constructor. This is a very bad pattern since this can be accessed by the new thread before it is fully initialized. I assume the main thread is calling new Class1() and new Class2(). Have the main thread also start the threads.

      Thread thread1 = new Thread(new Class1());
      thread1.start();
      Thread thread2 = new Thread(new Class2());
      thread2.start();
      
    • There is no way for a thread which is running on Class1 to access a subclass method. If you start new Thread(new Class1()) the thread won't even see any methods in Class2.

    Maybe I'm not understanding what you are saying. Post some small code samples so we can better address your issues.