Java new thread

In Java, a new thread can be created in several ways:

  1. Extending the Thread class: You can create a new thread by extending the Thread class and overriding the run() method.
    public class MyThread extends Thread {
     public void run() {
         // code to be executed by the thread
     }
    }
  2. Implementing the Runnable interface: You can create a new thread by implementing the Runnable interface and creating a separate class that implements it.
    public class MyRunnable implements Runnable {
     public void run() {
         // code to be executed by the thread
     }
    }
  3. Using the Thread class constructor: You can create a new thread by using the Thread class constructor and passing a Runnable object to it.
    Thread myThread = new Thread(new MyRunnable());
  4. Using the Executors class: You can create a new thread pool using the Executors class and submit a Runnable task to it.
    ExecutorService executor = Executors.newFixedThreadPool(5);
    executor.submit(new MyRunnable());
  5. Using the ThreadFactory interface: You can create a new thread using the ThreadFactory interface, which provides a way to create threads in a more flexible and customizable way.
    ThreadFactory threadFactory = new ThreadFactory() {
     public Thread newThread(Runnable r) {
         return new Thread(r, "MyThread");
     }
    };
    Thread myThread = threadFactory.newThread(new MyRunnable());

    Once you have created a new thread, you can start it using the start() method.

    myThread.start();

    Note that the start() method does not execute the thread immediately. Instead, it schedules the thread to be executed by the JVM. The thread will run until it completes its execution or is interrupted by another thread.

It's also important to note that in Java, threads are not guaranteed to run concurrently. The JVM may choose to run threads sequentially or concurrently, depending on various factors such as system load and thread priority.