Java多線程及線程安全實現(xiàn)方法解析
一、java多線程實現(xiàn)的兩種方式
1、繼承Thread
/** * * @version: 1.1.0 * @Description: 多線程 * @author: wsq * @date: 2020年6月8日下午2:25:33 */ public class MyThread extends Thread{ @Override public void run() { System.out.println("This is the first thread!"); } public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); } }
2、實現(xiàn) Runnable 接口
public class MultithreadingTest { public static void main(String[] args) { new Thread(() -> System.out.println("This is the first thread!")).start(); } }
或者
public class MyThreadImpl implements Runnable{ private int count = 5; @Override public void run() { // TODO Auto-generated method stub count--; System.out.println("Thread"+Thread.currentThread().getName()+"count:"+count); } }
二、解決線程不安全問題
/** * * @version: 1.1.0 * @Description: 測試類 * @author: wsq * @date: 2020年6月8日下午9:27:02 */ public class Test { public static void main(String[] args) { MyThreadImpl myThreadImpl = new MyThreadImpl(); Thread A = new Thread(myThreadImpl,"A"); Thread B = new Thread(myThreadImpl,"B"); Thread C = new Thread(myThreadImpl,"C"); Thread D = new Thread(myThreadImpl,"D"); Thread E = new Thread(myThreadImpl,"E"); A.start(); B.start(); C.start(); D.start(); E.start(); } }
打印結果為:
ThreadBcount:3
ThreadCcount:2
ThreadAcount:3
ThreadDcount:1
ThreadEcount:0
B和A共用一個線程,存在線程安全問題
改成:
public class MyThreadImpl implements Runnable{ private int count = 5; @Override // 使用同步解決線程安全問題 synchronized public void run() { // TODO Auto-generated method stub count--; System.out.println("Thread"+Thread.currentThread().getName()+"count:"+count); } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springboot2如何集成ElasticSearch6.4.3
這篇文章主要介紹了springboot2如何集成ElasticSearch6.4.3問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07SpringBoot/Spring?AOP默認動態(tài)代理方式實例詳解
這篇文章主要給大家介紹了關于SpringBoot/Spring?AOP默認動態(tài)代理方式的相關資料,Spring AOP是一款基于Java的AOP框架,其中默認采用動態(tài)代理方式實現(xiàn)AOP功能,本文將詳細介紹動態(tài)代理的實現(xiàn)原理和使用方法,需要的朋友可以參考下2023-03-03Mybatis中注入執(zhí)行sql查詢、更新、新增及建表語句案例代碼
這篇文章主要介紹了Mybatis中注入執(zhí)行sql查詢、更新、新增以及建表語句,主要說明一個另類的操作,注入sql,并使用mybatis執(zhí)行,結合案例代碼詳解講解,需要的朋友可以參考下2023-02-02Java編程實現(xiàn)的二維數(shù)組轉置功能示例
這篇文章主要介紹了Java編程實現(xiàn)的二維數(shù)組轉置功能,結合實例形式分析了Java二維數(shù)組的遍歷、運算、賦值等實現(xiàn)轉置的相關操作技巧,需要的朋友可以參考下2018-01-01SpringBoot使用責任鏈模式優(yōu)化業(yè)務邏輯中的if-else代碼
在開發(fā)過程中,我們經(jīng)常會遇到需要根據(jù)不同的條件執(zhí)行不同的邏輯的情況,我們可以考慮使用責任鏈模式來優(yōu)化代碼結構,使得代碼更加清晰、可擴展和易于維護2023-06-06解決@Validated注解無效,嵌套對象屬性的@NotBlank無效問題
這篇文章主要介紹了解決@Validated注解無效,嵌套對象屬性的@NotBlank無效問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10解讀httpclient的validateAfterInactivity連接池狀態(tài)檢測
這篇文章主要為大家介紹了httpclient的validateAfterInactivity連接池狀態(tài)檢測解讀*,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11