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:
-
Inheriting from the
Threadclass: Create a new class that extendsjava.lang.Thread, and override therun()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(); -
Implementing the
Runnableinterface: Create a class that implementsjava.lang.Runnable, and provide an implementation for therun()method. Then create aThreadobject, passing theRunnableobject 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.
-
Implementing the
Callableinterface and usingExecutorService: Thejava.util.concurrent.Callableinterface, similar toRunnable, represents a task that can be executed in another thread, but unlikeRunnable, thecall()method can return a result and throw exceptions. To execute aCallable, thread pools fromjava.util.concurrent.ExecutorServiceare 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(); }