Java多線程實現Runnable方式
本文為大家分享了Java多線程實現Runnable方式的具體方法,供大家參考,具體內容如下
(一)步驟
1.定義實現Runnable接口
2.覆蓋Runnable接口中的run方法,將線程要運行的代碼存放在run方法中。
3.通過Thread類建立線程對象。
4.將Runnable接口的子類對象作為實際參數傳遞給Thread類的構造函數。
為什么要講Runnable接口的子類對象傳遞給Thread的構造方法。因為自定義的方法的所屬的對象是Runnable接口的子類對象。
5.調用Thread類的start方法開啟線程并調用Runnable接口子類run方法。
(二)線程安全的共享代碼塊問題
目的:程序是否存在安全問題,如果有,如何解決?
如何找問題:
1.明確哪些代碼是多線程運行代碼。
2.明確共享數據
3.明確多線程運行代碼中哪些語句是操作共享數據的。
class Bank{ private int sum; public void add(int n){ sum+=n; System.out.println("sum="+sum); } } class Cus implements Runnable{ private Bank b=new Bank(); public void run(){ synchronized(b){ for(int x=0;x<3;x++) { b.add(100); } } } } public class BankDemo{ public static void main(String []args){ Cus c=new Cus(); Thread t1=new Thread(c); Thread t2=new Thread(c); t1.start(); t2.start(); } }
或者第二種方式,將同步代碼synchronized放在修飾方法中。
class Bank{ private int sum; public synchronized void add(int n){ Object obj=new Object(); sum+=n; try{ Thread.sleep(10); }catch(Exception e){ e.printStackTrace(); } System.out.println("sum="+sum); } } class Cus implements Runnable{ private Bank b=new Bank(); public void run(){ for(int x=0;x<3;x++) { b.add(100); } } } public class BankDemo{ public static void main(String []args){ Cus c=new Cus(); Thread t1=new Thread(c); Thread t2=new Thread(c); t1.start(); t2.start(); } }
總結:
1.在一個類中定義要處理的問題,方法。
2.在實現Runnable的類中重寫run方法中去調用已經定義的類中的要處理問題的方法。
在synchronized塊中接受要處理問題那個類的對象。
3.在main方法中去定義多個線程去執(zhí)行。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot實戰(zhàn)項目之谷歌瀏覽器全屏效果實現
這篇文章主要介紹了通過 Java SpringBoot來實現谷歌瀏覽器的全屏效果,希望頁面展示時可以實現全屏效果以提高用戶體驗。感興趣的小伙伴跟著小編往下看吧2021-09-09一次Spring無法啟動的問題排查實戰(zhàn)之字節(jié)碼篇
最近學習了spring相關知識,公司項目也用到了spring,下面這篇文章主要給大家介紹了一次Spring無法啟動的問題排查實戰(zhàn)之字節(jié)碼篇的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-04-04