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{@Overridepublic 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(); }}
打印結(jié)果為:
ThreadBcount:3ThreadCcount:2ThreadAcount:3ThreadDcount:1ThreadEcount: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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. jsp網(wǎng)頁實現(xiàn)貪吃蛇小游戲2. ASP.NET MVC遍歷驗證ModelState的錯誤信息3. jsp實現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫的方法4. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向5. ASP中if語句、select 、while循環(huán)的使用方法6. asp中response.write("中文")或者js中文亂碼問題7. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實現(xiàn)方法8. PHP設(shè)計模式中工廠模式深入詳解9. 刪除docker里建立容器的操作方法10. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明
