国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術文章
文章詳情頁

Java多線程及線程安全實現方法解析

瀏覽:105日期:2022-08-31 13:05:50

一、java多線程實現的兩種方式

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、實現 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: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); }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 澳门毛片免费观看 | 在线观看亚洲专区 | 欧美另类videosbestsex高清 | 一区二区三区欧美视频 | 亚洲国产日韩欧美一区二区三区 | 欧洲女同互慰在线视频 | 91热久久免费精品99 | 久久精品国产亚洲高清 | 亚洲天堂成人在线观看 | 国产一级毛片网站 | 在线观看毛片视频 | 国产在线观看高清不卡 | 一级毛片免费不卡夜夜欢 | 欧美成免费 | 欧美在线成人午夜网站 | 成人在线不卡 | 毛片欧美| 国产va精品网站精品网站精品 | 久久精品亚瑟全部免费观看 | 国产精品91在线播放 | 成网站在线观看人免费 | 曰本人做爰大片免费观看一 | 亚洲国产最新在线一区二区 | 亚洲色视频在线播放网站 | 亚洲天堂2018av | 久久精品国产亚洲高清 | 国产精品久久久久久久久久久久久久 | 成人入口 | 中国美女黄色一级片 | 一本久久a久久精品亚洲 | 2022日韩理论片在线观看 | 国内精品福利视频 | 可以免费看黄色的网站 | 精品国产欧美一区二区三区成人 | 女女同性一区二区三区四区 | 精品国产一区二区三区www | 成人免费影视网站 | 欧美日韩亚洲视频 | 美女黄色片免费 | 在线观看二区三区午夜 | 久久 精品 一区二区 |