Java多線程及線程安全實(shí)現(xiàn)方法解析
一、java多線程實(shí)現(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、實(shí)現(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. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)2. vue前端RSA加密java后端解密的方法實(shí)現(xiàn)3. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能4. 基于jsp+mysql實(shí)現(xiàn)在線水果銷售商城系統(tǒng)5. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財務(wù)記賬管理系統(tǒng)6. CSS可以做的幾個令你嘆為觀止的實(shí)例分享7. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享8. ASP中實(shí)現(xiàn)字符部位類似.NET里String對象的PadLeft和PadRight函數(shù)9. 利用CSS3新特性創(chuàng)建透明邊框三角10. 淺談由position屬性引申的css進(jìn)階討論

網(wǎng)公網(wǎng)安備