如何使用Java中的多執行緒實作並發程式設計?
在現代電腦處理器的發展中,我們看到了多核心處理器的出現,這為並發程式設計提供了更多的可能性。而Java作為一種廣泛使用的程式語言,提供了豐富的多執行緒函式庫,幫助開發者實現高效的並發程式設計。本文將介紹如何使用Java中的多執行緒實作並發編程,並提供程式碼範例。
在Java中,建立執行緒有兩種方式:繼承Thread類別和實作Runnable介面。
方式一:繼承Thread類別
class MyThread extends Thread { @Override public void run() { System.out.println("MyThread is running"); } } public class Main { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } }
方式二:實作Runnable介面
class MyRunnable implements Runnable { @Override public void run() { System.out.println("MyRunnable is running"); } } public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } }
class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } } public class Main { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Thread thread1 = new Thread(() -> { for (int i = 0; i < 1000000; i++) { counter.increment(); } }); Thread thread2 = new Thread(() -> { for (int i = 0; i < 1000000; i++) { counter.increment(); } }); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println("Count: " + counter.getCount()); } }
class Message { private String content; private boolean empty = true; public synchronized String read() { while (empty) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } empty = true; notifyAll(); return content; } public synchronized void write(String content) { while (!empty) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } empty = false; this.content = content; notifyAll(); } } public class Main { public static void main(String[] args) { Message message = new Message(); Thread producer = new Thread(() -> { String[] contents = {"Message 1", "Message 2", "Message 3"}; for (String content : contents) { message.write(content); } }); Thread consumer = new Thread(() -> { for (int i = 0; i < 3; i++) { System.out.println("Message received: " + message.read()); } }); producer.start(); consumer.start(); } }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { executor.submit(() -> { System.out.println("Task executed by " + Thread.currentThread().getName()); }); } executor.shutdown(); } }
以上是如何使用Java中的多執行緒實作並發程式設計?的詳細內容。更多資訊請關注PHP中文網其他相關文章!