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<Integer> {
public Integer call() {
// 線程執行的代碼
return 0;
}
}
public class Main {
public static void main(String[] args) {
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(callable);
try {
Integer result = future.get();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
executor.execute(new Runnable() {
public void run() {
// 線程執行的代碼
}
});
}
executor.shutdown();
}
}