在Java中分配多線程任務可以通過以下幾種方法實現:
class MyThread extends Thread {
public void run() {
// 任務代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
class MyRunnable implements Runnable {
public void run() {
// 任務代碼
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable();
MyRunnable runnable2 = new MyRunnable();
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyRunnable implements Runnable {
public void run() {
// 任務代碼
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new MyRunnable());
executorService.submit(new MyRunnable());
executorService.shutdown();
}
}
注意:在使用線程池時,務必在最后調用shutdown()方法關閉線程池,以便正確釋放資源。如果需要立即關閉線程池,可以使用shutdownNow()方法。