在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() {
// 線程要執行的代碼
return result;
}
}
ExecutorService executor = Executors.newFixedThreadPool(1);
MyCallable callable = new MyCallable();
Future<Integer> future = executor.submit(callable);
Integer result = future.get();
Runnable runnable = new Runnable() {
public void run() {
// 線程要執行的代碼
}
};
Thread thread = new Thread(runnable);
thread.start();
或者
Runnable runnable = () -> {
// 線程要執行的代碼
};
Thread thread = new Thread(runnable);
thread.start();
以上是幾種常見的實現多線程的方式,每種方式都有其適用的場景,可以根據具體需求選擇合適的方式來實現多線程。