在 C++ 和 Java 中實(shí)現(xiàn)多線程的方法有所不同。下面分別介紹兩種語言中的實(shí)現(xiàn)方式:
C++
C++11 標(biāo)準(zhǔn)引入了線程庫 <thread>
,可以方便地實(shí)現(xiàn)多線程。以下是使用 C++11 的 std::thread
創(chuàng)建和運(yùn)行線程的示例:
#include <iostream>
#include <thread>
void helloWorld() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
// 創(chuàng)建線程
std::thread t(helloWorld);
// 等待線程完成
t.join();
return 0;
}
Java
Java 自 JDK1.5 起提供了 java.util.concurrent
包,其中包含了豐富的多線程支持。以下是使用 Java 的 Thread
類創(chuàng)建和運(yùn)行線程的示例:
public class HelloWorldThread extends Thread {
public void run() {
System.out.println("Hello from thread " + Thread.currentThread().getId());
}
public static void main(String[] args) {
// 創(chuàng)建線程
Thread t = new HelloWorldThread();
// 啟動(dòng)線程
t.start();
}
}
另外,Java 還提供了 ExecutorService
接口和相關(guān)的實(shí)現(xiàn)類(如 ThreadPoolExecutor
和 Executors
工具類),用于更高效地管理和控制線程。