Sobes.tech
Junior

What Java language features can be used to create threads?

sobes.tech AI

Answer from AI

Creating a thread in Java can be done in several ways:

  1. Inheriting from the Thread class: Create a new class that extends java.lang.Thread, and override the run() method.

    // Creating a class that extends Thread
    class MyThread extends Thread {
        // Override the run method
        @Override
        public void run() {
            // Code to execute in the new thread
            System.out.println("Thread " + Thread.currentThread().getName() + " started.");
        }
    }
    

    Starting the thread:

    // Create an instance of the thread
    MyThread thread = new MyThread();
    // Start the thread
    thread.start();
    
  2. Implementing the Runnable interface: Create a class that implements java.lang.Runnable, and provide an implementation for the run() method. Then create a Thread object, passing the Runnable object to it.

    // Creating a class that implements Runnable
    class MyRunnable implements Runnable {
        // Implement the run method
        @Override
        public void run() {
            // Code to execute in the new thread
            System.out.println("Thread " + Thread.currentThread().getName() + " started.");
        }
    }
    

    Starting the thread:

    // Create an instance of Runnable
    MyRunnable runnable = new MyRunnable();
    // Create a Thread, passing the Runnable
    Thread thread = new Thread(runnable);
    // Start the thread
    thread.start();
    

    This method is preferable because it allows the class to inherit from other classes as well.

  3. Implementing the Callable interface and using ExecutorService: The java.util.concurrent.Callable interface, similar to Runnable, represents a task that can be executed in another thread, but unlike Runnable, the call() method can return a result and throw exceptions. To execute a Callable, thread pools from java.util.concurrent.ExecutorService are usually used.

    import java.util.concurrent.*;
    
    // Creating a class that implements Callable
    class MyCallable implements Callable<String> {
        // Implementing the call method that can return a result
        @Override
        public String call() throws Exception {
            // Code to execute in the new thread
            System.out.println("Thread " + Thread.currentThread().getName() + " started.");
            // Return the result
            return "Task completed successfully!";
        }
    }
    

    Starting and getting the result:

    import java.util.concurrent.*;
    
    // Creating a thread pool
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Creating a Callable instance
    MyCallable callable = new MyCallable();
    // Submitting the task and getting a Future to track the result
    Future<String> future = executor.submit(callable);
    
    try {
        // Getting the result of the task
        String result = future.get();
        System.out.println("Result: " + result);
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } finally {
        // Always shut down the ExecutorService
        executor.shutdown();
    }