溫馨提示×

java多線程實(shí)現(xiàn)的方法有哪些

小億
83
2023-12-28 11:46:22
欄目: 編程語言

Java實(shí)現(xiàn)多線程的方法有以下幾種:

  1. 繼承Thread類:創(chuàng)建一個(gè)繼承自Thread類的子類,并重寫run()方法,在run()方法中定義線程的執(zhí)行邏輯。
public class MyThread extends Thread {
    public void run() {
        // 線程的執(zhí)行邏輯
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 啟動(dòng)線程
    }
}
  1. 實(shí)現(xiàn)Runnable接口:創(chuàng)建一個(gè)實(shí)現(xiàn)了Runnable接口的類,并實(shí)現(xiàn)run()方法,在run()方法中定義線程的執(zhí)行邏輯。
public class MyRunnable implements Runnable {
    public void run() {
        // 線程的執(zhí)行邏輯
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start(); // 啟動(dòng)線程
    }
}
  1. 使用Callable和Future:創(chuàng)建一個(gè)實(shí)現(xiàn)了Callable接口的類,并實(shí)現(xiàn)call()方法,在call()方法中定義線程的執(zhí)行邏輯。使用ExecutorService的submit()方法提交Callable任務(wù),并通過Future對象獲取任務(wù)的返回結(jié)果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallable implements Callable<Integer> {
    public Integer call() {
        // 線程的執(zhí)行邏輯,返回一個(gè)結(jié)果
        return 1;
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        MyCallable callable = new MyCallable();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<Integer> future = executorService.submit(callable);
        int result = future.get(); // 獲取任務(wù)的返回結(jié)果
        System.out.println(result);
        executorService.shutdown();
    }
}
  1. 使用線程池:創(chuàng)建一個(gè)線程池,通過submit()方法提交Runnable或Callable任務(wù),線程池會(huì)自動(dòng)分配線程執(zhí)行任務(wù)。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyRunnable implements Runnable {
    public void run() {
        // 線程的執(zhí)行邏輯
    }
}

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 創(chuàng)建一個(gè)固定大小的線程池
        executorService.execute(new MyRunnable()); // 提交任務(wù)
        executorService.shutdown(); // 關(guān)閉線程池
    }
}

0