Java開啟多線程的常見方法有以下幾種:
class MyThread extends Thread {
public void run() {
// 線程執行的代碼
}
}
MyThread thread = new MyThread();
thread.start();
class MyRunnable implements Runnable {
public void run() {
// 線程執行的代碼
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
// 線程執行的代碼
return 1;
}
}
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(callable);
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Runnable() {
public void run() {
// 線程執行的代碼
}
});
這些方法都可以用來創建并啟動一個新的線程,根據具體情況選擇使用。