Search code examples
javamultithreadinguser-interfacethread-sleep

Does each class have its own Thread by default?


I'm working with a GUI and I'm using

Thread.sleep();

in some of the classes, and I'm wondering if I need to create a separate Thread for my Main class (the GUI class), or if each class has a separate Thread by default. Note, the reason that I bring up Thread.sleep(); in the first place is that when working with GUI's Thread.sleep(); pretty much freezes your GUI. Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.


Solution

  • Thread.sleep() is a static method of Thread class. Hence, whichever class you place in a method, during runtime, if a thread call flow encounters this class method where Thread.sleep() in invoked, the thread will be blocked for that amount of time.

    Your Question:
    Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.

    • each class has a separate Thread by default -- INCORRECT Statement
      -- Thread class is not inherited by every class
      -- In normal sense, Thread is a call flow. It executes whichever class it encounters thru its method calls.
      -- Class and Thread are 2 separate concepts.
      ---- Class is a definition of an entity,it cannot run by itself, it can be loaded, instantiated with data, method calls can be done and garbage collected.
      ---- Thread is an execution entity at run-time.It can be started, runnable, blocked, stopped. To support this concept, Java has provided Thread class or Runnable interface to extend/implement respectively.

    • do I need to create a separate Thread for my Main class?
      -- your mainclass will be executed in a MainThread which is instantiated and started by your JVM.
      -- It is better to define a seperate user-defined Thread to start your GUI.
      -- If either in the MainThread (or) user-defined Thread, if it encounters Thread.sleep() during call flow, that particular thread will be blocked.

    One more thing, your question is not clear on your need for usage of Thread.sleep(). You just have given a reason of the resultant usage of it but not the need for usage.