一、多線程基礎
多線程是指在一個進程內同時執行多個並發任務的方式,多線程可以提高程序的響應速度和程序的並發處理能力。
在Java中,我們可以通過繼承Thread類或實現Runnable接口來創建線程。以下是一個實現Runnable接口的簡單示例代碼:
public class MyRunnable implements Runnable { public void run() { System.out.println("線程運行中"); } } public class Test { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } }
上述代碼中,創建了一個MyRunnable類,實現了Runnable接口。MyRunnable類中的run()方法是子線程要執行的任務。在Test類中,創建了一個Thread對象,傳入MyRunnable對象。調用Thread的start()方法會啟動線程,執行MyRunnable中的run()方法。
二、線程同步
在多線程環境下,不同線程可能會同時訪問共享資源,如果兩個線程同時修改同一個變量,那麼可能就會出現數據不一致的問題。因此,我們需要對共享資源進行同步,使得同一時間只有一個線程能夠訪問共享資源。
Java中提供了synchronized關鍵字來實現線程同步。在使用synchronized關鍵字時,需要制定一個共享資源,只有獲取到該共享資源的鎖的線程才能訪問共享資源。以下是一個簡單示例代碼:
public class MyCounter { private int count; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } } public class Test { public static void main(String[] args) throws InterruptedException { MyCounter counter = new MyCounter(); Thread thread1 = new Thread(() -> { for (int i = 0; i { for (int i = 0; i < 10000; i++) { counter.increment(); } }); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println(counter.getCount()); } }
上述代碼中,MyCounter類中的increment()方法和getCount()方法都是用synchronized關鍵字進行了同步處理,保證了對count變量的訪問是線程安全的。Test類中創建了兩個線程來分別調用increment()方法,執行完畢後輸出count變量的值。由於共享資源已經被同步,因此輸出的count變量的值為20000。
三、線程池
多線程一般都是通過創建線程對象的方式來實現,但是頻繁地創建和銷毀線程對象也會帶來一定的開銷。線程池是一種能夠有效管理多個線程的機制,可以循環利用已經創建好的線程,從而避免頻繁創建和銷毀線程。
Java中提供了Executor框架,可以方便地創建和管理線程池。以下是一個簡單的線程池示例代碼:
public class Test { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { executorService.execute(new MyTask()); } executorService.shutdown(); } } public class MyTask implements Runnable { public void run() { System.out.println("線程池執行任務中"); } }
上述代碼中,創建了一個包含5個線程的線程池,並將10個MyTask任務放入線程池中執行。ExecutorService的execute()方法可以將任務放入線程池中執行,而shutdown()方法可以關閉線程池。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/157970.html