在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()方法。