深入探究一下Java中不同的線程間數(shù)據(jù)通信方式
1、多線程如何共享數(shù)據(jù)
多線程數(shù)據(jù)共享可以分為以下2種情況,線程實(shí)現(xiàn)代碼相同及線程實(shí)現(xiàn)代碼不同。
線程實(shí)現(xiàn)代碼相同
即runnable中的代碼一致,這樣可以直接在實(shí)現(xiàn)中定義成員變量直接共享
public class SharedSameRunnableDemo { public static void main(String[] args) { Runnable runnable = new MySameRunnable(); Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread1.start(); thread2.start(); } private static class MySameRunnable implements Runnable { private int sharedData = 0; @Override public synchronized void run() { for (int i = 0; i < 5; i++) { sharedData++; System.out.println("Thread: " + Thread.currentThread().getName() + ", sharedData: " + sharedData); } } } }
在上面的示例中,我們定義了一個(gè)名為 MySameRunnable 的內(nèi)部類它的共享變量是sharedData,它實(shí)現(xiàn)了Runnable 接口,并重寫了 run() 方法。在 run() 方法中,我們使用了 synchronized 關(guān)鍵字來(lái)保證線程安全。然后在main() 方法中,我們創(chuàng)建了一個(gè) MySameRunnable 實(shí)例 runnable,并將其傳入兩個(gè)不同的線程對(duì)象中。最后啟動(dòng)這兩個(gè)線程。由于這兩個(gè)線程共享同一個(gè) MySameRunnable 實(shí)例,因此它們執(zhí)行的代碼是相同的,并且可以訪問(wèn)和修改sharedData 變量。通過(guò)這種方式,就可以實(shí)現(xiàn)多個(gè)線程共享數(shù)據(jù),并確保線程安全。
線程實(shí)現(xiàn)代碼不相同
即runnable中的代碼不一致,MyRunnable1 MyRunnable2,利用一個(gè)對(duì)象SharedData,把runnable中的方法封裝到這個(gè)對(duì)象中去,數(shù)據(jù)也在這個(gè)對(duì)象中。如果多個(gè)線程實(shí)現(xiàn)的代碼不同,并且需要共享變量,可以使用一個(gè)單獨(dú)的類來(lái)存儲(chǔ)這些共享變量,并將它傳遞給所有的 Runnable 實(shí)例。以下是一個(gè)簡(jiǎn)單的示例代碼:
public class SharedDifferentRauuableDemo { public static void main(String[] args) { SharedData sharedData = new SharedData(); Thread thread1 = new Thread(new MyRunnable1(sharedData)); Thread thread2 = new Thread(new MyRunnable2(sharedData)); thread1.start(); thread2.start(); } private static class SharedData { private int data = 0; public synchronized void increment() { data++; System.out.println("IncrementThread: " + data); } public synchronized void decrement() { data--; System.out.println("DecrementThread: " + data); } } private static class MyRunnable1 implements Runnable { private SharedData sharedData; public MyRunnable1(SharedData sharedData) { this.sharedData = sharedData; } @Override public void run() { for (int i = 0; i < 5; i++) { sharedData.increment(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } private static class MyRunnable2 implements Runnable { private SharedData sharedData; public MyRunnable2(SharedData sharedData) { this.sharedData = sharedData; } @Override public void run() { for (int i = 0; i < 5; i++) { sharedData.decrement(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
在上面的示例中,我們定義了一個(gè) SharedData 類來(lái)存儲(chǔ)共享變量 data。這個(gè)類包含兩個(gè)同步方法 increment() 和 decrement(),用于增加和減少 data 的值,并輸出當(dāng)前的值。然后我們創(chuàng)建了兩個(gè) MyRunnable1 和 MyRunnable2 實(shí)例,它們分別傳遞了相同的 SharedData 對(duì)象。在 run() 方法中,它們調(diào)用 SharedData 對(duì)象的 increment() 和 decrement() 方法來(lái)進(jìn)行數(shù)據(jù)修改,并使用 Thread.sleep() 方法讓線程休眠一段時(shí)間。
通過(guò)這種方式,就可以實(shí)現(xiàn)多個(gè)線程共享數(shù)據(jù),并確保線程安全。
2、子線程如何繼承父線程數(shù)據(jù)
通過(guò) InteritableThreadLocal實(shí)現(xiàn)共享
public class InheritableThreadLocalDemo { private static final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>(); public static void main(String[] args) { inheritableThreadLocal.set("Hello, World!"); Thread parentThread = new Thread(() -> { System.out.println("Parent Thread: " + inheritableThreadLocal.get()); inheritableThreadLocal.set("Hello from Parent Thread!"); Thread childThread = new Thread(() -> { System.out.println("Child Thread: " + inheritableThreadLocal.get()); }); childThread.start(); try { childThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Parent Thread: " + inheritableThreadLocal.get()); }); parentThread.start(); try { parentThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main Thread: " + inheritableThreadLocal.get()); inheritableThreadLocal.remove(); } }
在上面的示例中,我們創(chuàng)建了一個(gè) InheritableThreadLocal 對(duì)象,并將其設(shè)置為“Hello, World!”。然后,我們創(chuàng)建了一個(gè)名為“parentThread”的線程,并在其中輸出 inheritableThreadLocal 的值。接下來(lái),我們?cè)诟妇€程中將 inheritableThreadLocal 的值設(shè)置為“Hello from Parent Thread!”,并創(chuàng)建了一個(gè)名為“childThread”的線程,在其中輸出 inheritableThreadLocal 的值。
注意:由于 InheritableThreadLocal 是可繼承的,所以在子線程中也能夠獲取到父線程中設(shè)置的值。因此,當(dāng)我們?cè)谧泳€程中輸出 inheritableThreadLocal 的值時(shí),我們將看到輸出“Hello from Parent Thread!”。
最后,我們分別在父線程、子線程和主線程中輸出 inheritableThreadLocal 的值。由于我們?cè)诿總€(gè)線程中都設(shè)置了 inheritableThreadLocal 的值,所以每個(gè)線程都將輸出不同的值。
請(qǐng)注意,在程序的結(jié)尾處,我們調(diào)用了 inheritableThreadLocal.remove() 方法來(lái)清除 InheritableThreadLocal 對(duì)象的值,并釋放相關(guān)的資源。這是一種良好的習(xí)慣,可以避免內(nèi)存泄漏和數(shù)據(jù)污染等問(wèn)題。
3、相關(guān)問(wèn)題
1.請(qǐng)簡(jiǎn)述Java中的多線程通信機(jī)制,并解釋一下為什么需要多線程通信?
答:Java中的多線程通信機(jī)制是通過(guò)使用管道和共享變量來(lái)實(shí)現(xiàn)的。管道可以用來(lái)實(shí)現(xiàn)多個(gè)線程之間的數(shù)據(jù)傳遞和同步,共享變量可以用來(lái)實(shí)現(xiàn)多個(gè)線程之間的數(shù)據(jù)共享和同步。
2.Java 中,在多個(gè)線程之間共享數(shù)據(jù)的方式主要有以下幾種:
1)共享變量:可以將需要共享的變量定義為靜態(tài)變量或公共變量,然后通過(guò)同步控制機(jī)制(例如 synchronized 關(guān)鍵字、Lock 接口等)保證多線程訪問(wèn)這些變量時(shí)的安全性。
2)ThreadLocal:通過(guò) ThreadLocal 類可以在每個(gè)線程中創(chuàng)建獨(dú)立的變量副本,從而避免了對(duì)共享變量的競(jìng)爭(zhēng)。
3)Callable 和 Future 接口:在子線程執(zhí)行任務(wù)后,可以通過(guò) Callable 和 Future 接口返回結(jié)果給主線程。主線程可以通過(guò) Future.get() 方法獲取子線程的執(zhí)行結(jié)果,從而完成數(shù)據(jù)共享。
4)BlockingQueue:可以使用 BlockingQueue 來(lái)實(shí)現(xiàn)數(shù)據(jù)共享和通信,生產(chǎn)者線程向 BlockingQueue 中添加數(shù)據(jù),消費(fèi)者線程從隊(duì)列中獲取數(shù)據(jù)。
5)CyclicBarrier 和 CountDownLatch:可以使用 CyclicBarrier 和 CountDownLatch 等同步工具來(lái)協(xié)調(diào)多個(gè)線程之間的操作,從而實(shí)現(xiàn)數(shù)據(jù)共享。
到此這篇關(guān)于深入探究一下Java中不同的線程間數(shù)據(jù)通信方式的文章就介紹到這了,更多相關(guān)Java線程數(shù)據(jù)通信方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot使用jsr303校驗(yàn)的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot使用jsr303校驗(yàn)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10淺談Spring框架中@Autowired和@Resource的區(qū)別
最近review別人代碼的時(shí)候,看到了一些@Autowired不一樣的用法,覺(jué)得有些意思,下面這篇文章主要給大家介紹了關(guān)于Spring框架中@Autowired和@Resource區(qū)別的相關(guān)資料,需要的朋友可以參考下2022-10-10Java 中POI 導(dǎo)入EXCEL2003 和EXCEL2007的實(shí)現(xiàn)方法
這篇文章主要介紹了Java 中POI 導(dǎo)入EXCEL2003 和EXCEL2007的實(shí)現(xiàn)方法的相關(guān)資料,希望通過(guò)本文大家能掌握理解這種方法,需要的朋友可以參考下2017-09-09Ehcache簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Ehcache簡(jiǎn)介,使用Spring的AOP進(jìn)行整合,可以靈活的對(duì)方法的返回結(jié)果對(duì)象進(jìn)行緩存2017-07-07SpringAop切入點(diǎn)execution表達(dá)式的深入講解
Spring AOP 可能會(huì)經(jīng)常使用 execution切入點(diǎn)指示符,下面這篇文章主要給大家介紹了關(guān)于SpringAop切入點(diǎn)execution表達(dá)式的相關(guān)資料,需要的朋友可以參考下2021-08-08SpringCloud全局過(guò)慮器GlobalFilter的用法小結(jié)
這篇文章主要介紹了SpringCloud全局過(guò)慮器GlobalFilter的使用,全局過(guò)慮器使用非常廣泛,比如驗(yàn)證是否登錄,全局性的處理,黑名單或白名單的校驗(yàn)等,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07