Java Multithreading: Extending Thread, Implementing Runnable, and Using ExecutorService with Callable and Future
This article explains three primary ways to create multithreaded Java programs—extending Thread, implementing Runnable, and employing ExecutorService with Callable and Future—providing code examples, execution details, and a complete runnable example that demonstrates thread creation, execution, and result retrieval.
Java provides three main approaches for implementing multithreading: extending the Thread class, implementing the Runnable interface, and using the ExecutorService framework together with Callable and Future for tasks that return results.
1. Extending Thread – Create a subclass of Thread and override its run() method. The thread is started by calling start() on an instance of the subclass.
public class MyThread extends Thread {
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();2. Implementing Runnable – When a class already extends another class, it can implement Runnable instead. The run() method contains the task logic, and a Thread is created with the Runnable instance.
public class MyThread extends OtherClass implements Runnable {
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();The Thread class internally calls the supplied Runnable 's run() method:
public void run() {
if (target != null) {
target.run();
}
}3. Using ExecutorService, Callable, and Future – The Executor framework (available since JDK 1.5) enables thread‑pool management and tasks that return results. A task implements Callable; submitting it to an ExecutorService returns a Future from which the result can be obtained.
import java.util.concurrent.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("----程序开始运行----");
Date date1 = new Date();
int taskSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
List<Future> list = new ArrayList<>();
for (int i = 0; i < taskSize; i++) {
Callable c = new MyCallable(i + " ");
Future f = pool.submit(c);
list.add(f);
}
pool.shutdown();
for (Future f : list) {
System.out.println(">>>" + f.get().toString());
}
Date date2 = new Date();
System.out.println("----程序结束运行----,程序运行时间【" + (date2.getTime() - date1.getTime()) + "毫秒】");
}
}
class MyCallable implements Callable<Object> {
private String taskNum;
MyCallable(String taskNum) { this.taskNum = taskNum; }
public Object call() throws Exception {
System.out.println(">>>" + taskNum + "任务启动");
Date dateTmp1 = new Date();
Thread.sleep(1000);
Date dateTmp2 = new Date();
long time = dateTmp2.getTime() - dateTmp1.getTime();
System.out.println(">>>" + taskNum + "任务终止");
return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";
}
}The code demonstrates creating a fixed‑size thread pool, submitting multiple Callable tasks, retrieving their results via Future, and measuring execution time. Additional utility methods of Executors (e.g., newCachedThreadPool, newSingleThreadExecutor, newScheduledThreadPool) are also described.
Source: blog.csdn.net/aboy123/article/details/38307539
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
