Threads in Java

To create a thread:

  • Create a descendant of the Thread class and override its run() method;
  • Create an object of the Thread class by passing it an instance of the class that implements the Runnable interface in the constructor. This interface contains a run() method that will run on a new thread. The thread will finish executing when its run() method finishes.
  • Call the submit() method on an instance of the class implementing the ExecutorService interface, passing it as a parameter an instance of the class implementing the Runnable or Callable interface (contains the call() method, which describes the execution logic).

Difference between Thread and Runnable

Thread is a class, some kind of add-on over a physical thread.

Runnable is an interface that abstracts the task at hand.

In addition to the fact that Runnable helps to solve the problem of multiple inheritance, the undoubted advantage of using it is that it allows you to logically separate the logic of task execution from direct flow control.

Difference between start() and run() methods

Even though start() calls the run() method internally, it is not the same as simply calling run(). If run() is called as a normal method, then it is called on the same thread and no new thread is started, as it does when you call start().

How do I force a thread to start?

No way. There is absolutely no way to force a thread to start in Java. This is controlled by the JVM and Java does not provide any API to control this process.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed