Java實現多線程的方法有三種:
class MyThread extends Thread {
public void run() {
// 線程執行的代碼
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyRunnable implements Runnable {
public void run() {
// 線程執行的代碼
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyRunnable implements Runnable {
public void run() {
// 線程執行的代碼
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(new MyRunnable());
executor.shutdown();
}
}