在Java中分配多線程任務(wù)可以通過以下幾種方法實(shí)現(xiàn):
class MyThread extends Thread {
public void run() {
// 任務(wù)代碼
}
}
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() {
// 任務(wù)代碼
}
}
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() {
// 任務(wù)代碼
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new MyRunnable());
executorService.submit(new MyRunnable());
executorService.shutdown();
}
}
注意:在使用線程池時(shí),務(wù)必在最后調(diào)用shutdown()方法關(guān)閉線程池,以便正確釋放資源。如果需要立即關(guān)閉線程池,可以使用shutdownNow()方法。