深入解析Java多執行緒:探究不同的實作方法,需要具體程式碼範例
摘要:
Java作為廣泛使用的程式語言,提供了豐富的多線程支援。本文將深入探討Java多執行緒的實作方法,包括繼承Thread類別、實作Runnable介面以及使用執行緒池。透過具體的程式碼範例,讀者將能夠更好地理解和運用這些方法。
public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread 1: " + i); } } } public class Main { public static void main(String[] args) { MyThread thread1 = new MyThread(); thread1.start(); for (int i = 0; i < 10; i++) { System.out.println("Main thread: " + i); } } }
public class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread 2: " + i); } } } public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread2 = new Thread(myRunnable); thread2.start(); for (int i = 0; i < 10; i++) { System.out.println("Main thread: " + i); } } }
public class MyTask implements Runnable { private int taskId; public MyTask(int taskId) { this.taskId = taskId; } @Override public void run() { System.out.println("Task " + taskId + " is running."); } } public class Main { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { MyTask task = new MyTask(i); executorService.execute(task); } executorService.shutdown(); } }
參考文獻:
以上是深入解析Java多執行緒:探究不同的實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!