Sobes.tech
Junior

What Java programming language features can be used to create threads?

sobes.tech AI

Answer from AI

  1. Inheritance from the Thread class:
// Creating a class that inherits from Thread
class MyThread extends Thread {
    @Override
    public void run() {
        // Thread execution logic
    }
}

// Creating and starting the thread
MyThread thread = new MyThread();
thread.start();
  1. Implementing the Runnable interface:
// Creating a class that implements Runnable
class MyRunnable implements Runnable {
    @Override
    public void run() {
        // Thread execution logic
    }
}

// Creating a thread using Runnable
Thread thread = new Thread(new MyRunnable());
thread.start();
  1. Using thread pools (ExecutorService) from the java.util.concurrent package:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// Creating a thread pool
ExecutorService executor = Executors.newFixedThreadPool(5);

// Submitting a task for execution
executor.execute(new MyRunnable());

// Shutting down the pool
executor.shutdown();
  1. Using Callable and Future to obtain execution results:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

// Creating a task with a return value
class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "Thread execution result";
    }
}

// Creating a thread pool
ExecutorService executor = Executors.newSingleThreadExecutor();

// Submitting a task and obtaining a Future
Future<String> future = executor.submit(new MyCallable());

try {
    // Getting the result
    String result = future.get();
} catch (Exception e) {
    // Handling exceptions
}

// Shutting down the pool
executor.shutdown();
What Java programming language features can be used… - sobes.tech