Java多線程實(shí)現(xiàn)Runnable方式
本文為大家分享了Java多線程實(shí)現(xiàn)Runnable方式的具體方法,供大家參考,具體內(nèi)容如下
(一)步驟
1.定義實(shí)現(xiàn)Runnable接口
2.覆蓋Runnable接口中的run方法,將線程要運(yùn)行的代碼存放在run方法中。
3.通過Thread類建立線程對象。
4.將Runnable接口的子類對象作為實(shí)際參數(shù)傳遞給Thread類的構(gòu)造函數(shù)。
為什么要講Runnable接口的子類對象傳遞給Thread的構(gòu)造方法。因?yàn)樽远x的方法的所屬的對象是Runnable接口的子類對象。
5.調(diào)用Thread類的start方法開啟線程并調(diào)用Runnable接口子類run方法。
(二)線程安全的共享代碼塊問題
目的:程序是否存在安全問題,如果有,如何解決?
如何找問題:
1.明確哪些代碼是多線程運(yùn)行代碼。
2.明確共享數(shù)據(jù)
3.明確多線程運(yùn)行代碼中哪些語句是操作共享數(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();
}
}
總結(jié):
1.在一個(gè)類中定義要處理的問題,方法。
2.在實(shí)現(xiàn)Runnable的類中重寫run方法中去調(diào)用已經(jīng)定義的類中的要處理問題的方法。
在synchronized塊中接受要處理問題那個(gè)類的對象。
3.在main方法中去定義多個(gè)線程去執(zhí)行。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解Java中Thread 和Runnable區(qū)別
- java實(shí)現(xiàn)Runnable接口適合資源的共享
- 淺析Java中Runnable和Thread的區(qū)別
- Java 線程對比(Thread,Runnable,Callable)實(shí)例詳解
- java實(shí)現(xiàn)多線程的兩種方式繼承Thread類和實(shí)現(xiàn)Runnable接口的方法
- java線程之使用Runnable接口創(chuàng)建線程的方法
- JAVA多線程Thread和Runnable的實(shí)現(xiàn)
- Java向Runnable線程傳遞參數(shù)方法實(shí)例解析
相關(guān)文章
SpringSecurity 手機(jī)號登錄功能實(shí)現(xiàn)
這篇文章主要介紹了SpringSecurity 手機(jī)號登錄功能實(shí)現(xiàn),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2023-12-12
SpringBoot實(shí)戰(zhàn)項(xiàng)目之谷歌瀏覽器全屏效果實(shí)現(xiàn)
這篇文章主要介紹了通過 Java SpringBoot來實(shí)現(xiàn)谷歌瀏覽器的全屏效果,希望頁面展示時(shí)可以實(shí)現(xiàn)全屏效果以提高用戶體驗(yàn)。感興趣的小伙伴跟著小編往下看吧2021-09-09
Java HttpClient實(shí)現(xiàn)socks代理的示例代碼
這篇文章主要介紹了Java HttpClient 實(shí)現(xiàn) socks 代理的示例代碼,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-11-11
SSh結(jié)合Easyui實(shí)現(xiàn)Datagrid的分頁顯示
這篇文章主要為大家詳細(xì)介紹了SSh結(jié)合Easyui實(shí)現(xiàn)Datagrid的分頁顯示的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-06-06
舉例講解Java的RTTI運(yùn)行時(shí)類型識別機(jī)制
這篇文章主要介紹了Java的RTTI運(yùn)行時(shí)類型識別機(jī)制,包括泛化的Class引用以及類型檢查instanceof等知識點(diǎn),需要的朋友可以參考下2016-05-05
一次Spring無法啟動(dòng)的問題排查實(shí)戰(zhàn)之字節(jié)碼篇
最近學(xué)習(xí)了spring相關(guān)知識,公司項(xiàng)目也用到了spring,下面這篇文章主要給大家介紹了一次Spring無法啟動(dòng)的問題排查實(shí)戰(zhàn)之字節(jié)碼篇的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04

