Junior
What Java programming language features can be used to create threads?
sobes.tech AI
Answer from AI
- Inheritance from the
Threadclass:
// 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();
- Implementing the
Runnableinterface:
// 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();
- Using thread pools (
ExecutorService) from thejava.util.concurrentpackage:
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();
- Using
CallableandFutureto 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();