Java實現多線程的方式有以下幾種:
class MyThread extends Thread {
public void run() {
// 線程要執行的任務
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyRunnable implements Runnable {
public void run() {
// 線程要執行的任務
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {
public String call() {
// 線程要執行的任務
return "任務執行結果";
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyCallable callable = new MyCallable();
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(callable);
String result = future.get();
System.out.println(result);
executorService.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
executorService.execute(new Runnable() {
public void run() {
// 線程要執行的任務
}
});
}
executorService.shutdown();
}
}