溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java多線程如何實(shí)現(xiàn)Runnable方式

發(fā)布時(shí)間:2021-08-06 11:15:19 來(lái)源:億速云 閱讀:131 作者:小新 欄目:編程語(yǔ)言

這篇文章將為大家詳細(xì)講解有關(guān)Java多線程如何實(shí)現(xiàn)Runnable方式,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

具體內(nèi)容如下

(一)步驟

 1.定義實(shí)現(xiàn)Runnable接口

 2.覆蓋Runnable接口中的run方法,將線程要運(yùn)行的代碼存放在run方法中。

3.通過Thread類建立線程對(duì)象。

4.將Runnable接口的子類對(duì)象作為實(shí)際參數(shù)傳遞給Thread類的構(gòu)造函數(shù)。

  為什么要講Runnable接口的子類對(duì)象傳遞給Thread的構(gòu)造方法。因?yàn)樽远x的方法的所屬的對(duì)象是Runnable接口的子類對(duì)象。

5.調(diào)用Thread類的start方法開啟線程并調(diào)用Runnable接口子類run方法。

(二)線程安全的共享代碼塊問題

目的:程序是否存在安全問題,如果有,如何解決?

如何找問題:

1.明確哪些代碼是多線程運(yùn)行代碼。

2.明確共享數(shù)據(jù)

3.明確多線程運(yùn)行代碼中哪些語(yǔ)句是操作共享數(shù)據(jù)的。

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(); 
   
   
  } 
 
 
}

關(guān)于“Java多線程如何實(shí)現(xiàn)Runnable方式”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI