一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - 利用synchronized實現線程同步的案例講解

利用synchronized實現線程同步的案例講解

2021-08-11 11:24Chin_style Java教程

這篇文章主要介紹了利用synchronized實現線程同步的案例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

一、前期基礎知識儲備

(1)線程同步的定義:多線程之間的同步。

(2)多線程同步原因:一個多線程的程序如果是通過Runnable接口實現的,則意味著類中的屬性將被多個線程共享,由此引出資源的同步問題,即當多個線程要操作同一資源時,有可能出現錯誤。

(3)實現多線程同步的方式——引入同步機制:在線程使用一個資源時為其加鎖,這樣其他的線程便不能訪問那個資源了,直到解鎖后才可以訪問。——這樣做的結果,所有線程間會有資源競爭,但是所有競爭的資源是同步的,刷新的,動態的,不會因為線程間的競爭,導致資源“過度消耗”或者“虛擬消耗”。

上代碼,具體展示“過度消耗/虛擬消耗”問題:

  1. public class TestTicketRunnable{
  2. public static void main(String[] a){
  3. TicketThread tThread = new TicketThread();
  4. new Thread(tThread).start();
  5. new Thread(tThread).start();
  6. new Thread(tThread).start();
  7. }
  8. };
  9. class TicketThread implements Runnable {
  10. private int ticket = 5;
  11. public void run(){
  12. for (int i = 0; i < 5; i++){
  13. if (ticket > 0){
  14. try {
  15. Thread.sleep(300);
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. System.out.println(Thread.currentThread().getName() + "賣票:ticket = " + ticket--);
  20. }
  21. }
  22. }
  23. };

運行結果:

  1. Thread-0賣票:ticket = 5
  2. Thread-2賣票:ticket = 5 //虛擬消耗
  3. Thread-1賣票:ticket = 4
  4. Thread-1賣票:ticket = 2
  5. Thread-2賣票:ticket = 3
  6. Thread-0賣票:ticket = 3 //虛擬消耗
  7. Thread-0賣票:ticket = -1 //過度消耗
  8. Thread-1賣票:ticket = 1
  9. Thread-2賣票:ticket = 0

如上所見,票一共5張,三個線程調用買票,線程1網上賣了售票第1張,緊接著線程2線下也賣了“第一張”出現了“虛擬消耗”的問題;線程3黃牛黨賣了最后1張票,線程1網上又賣了最后1張,出現了“過度消耗”的問題,這兩種問題都是實際生活中不可能發生的,但是在這個3個線程執行中卻出現了,那一定是有問題的,問題的根源就在于,三個渠道的“售票員”不在一個頻道上辦事,或者說沒有相互之間同步所共享的資源,導致這一問題的根本原因,就是相互之間實現方式不同步。

二、使用synchronized實現同步機制

synchronized關鍵字:Java語言的關鍵字,可用來給對象和方法或者代碼塊加鎖,當它鎖定一個方法或者一個代碼塊的時候,同一時刻最多只有一個線程執行這段代碼。

當兩個并發線程訪問同一個對象object中的這個加鎖同步代碼塊時,一個時間內只能有一個線程得到執行。另一個線程必須等待當前線程執行完這個代碼塊以后才能執行該代碼塊。

它包括兩種用法:synchronized 方法和 synchronized 塊。

即實現線程間同步的方式有兩種:

①使用synchronized同步代碼塊;

②使用synchronized關鍵字創建synchronized()方法

下面分別進行解析,對上面售票的代碼進行改造:

①代碼——使用synchronized同步代碼塊

  1. class TicketThread implements Runnable {
  2. private int ticket = 5;
  3. public void run(){
  4. for (int i = 0; i < 5; i++){
  5. synchronized(this){
  6. if (ticket > 0){
  7. try {
  8. Thread.sleep(300);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. System.out.println(Thread.currentThread().getName() + "賣票:ticket = " + ticket--);
  13. }
  14. }
  15. }
  16. }
  17. }

②代碼——使用synchronized關鍵字創建synchronized()方法

  1. class TicketThreadMethod implements Runnable {
  2. private int ticket = 5;
  3. public void run(){
  4. for (int i = 0; i < 5; i++){
  5. this.sale();
  6. }
  7. }
  8. public synchronized void sale(){
  9. if (ticket > 0){
  10. try {
  11. Thread.sleep(300);
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. System.out.println(Thread.currentThread().getName() + "賣票:ticket = " + ticket--);
  16. }
  17. }
  18. }

三、synchronized方法和synchronized同步代碼塊的區別:

synchronized同步代碼塊只是鎖定了該代碼塊,代碼塊外面的代碼還是可以被訪問的。

synchronized方法是粗粒度的并發控制,某一個時刻只能有一個線程執行該synchronized方法。

synchronized同步代碼塊是細粒度的并發控制,只會將塊中的代碼同步,代碼塊之外的代碼可以被其他線程同時訪問。

補充:多線程同步鎖synchronized(對象鎖與全局鎖)總結

1.synchronized同步鎖的引入

  1. /*
  2. * 非線程安全
  3. * */
  4. //多個線程共同訪問一個對象中的實例變量,則會出現"非線程安全"問題
  5. class MyRunnable1 implements Runnable{
  6. private int num = 10;
  7. public void run() {
  8. try {
  9. if(num > 0) {
  10. System.out.println(""+Thread.currentThread().getName()+"開始"+",num= "+num--);
  11. Thread.sleep(1000);
  12. System.out.println(""+Thread.currentThread().getName()+"結束");
  13. }
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }public class Test5_5{
  19. public static void main(String[] args) {
  20. MyRunnable1 myRunnable1 = new MyRunnable1();
  21. Thread thread1 = new Thread(myRunnable1,"線程1");
  22. Thread thread2 = new Thread(myRunnable1,"線程2");
  23. thread1.start();
  24. thread2.start();
  25. }
  26. }

利用synchronized實現線程同步的案例講解

上例說明兩個線程同時訪問一個沒有同步的方法,如果兩個線程同時操作業務對象中的實例變量,則會出現“線程不安全”問題。

由此我們引入synchronized關鍵字來實現同步問題:

在Java中使用synchronized關鍵字控制線程同步,控制synchronized代碼段不被多個線程同時執行,synchronized即可以使用在方法上也可以使用在代碼塊中。

2. 對象鎖

(1)synchronized方法(對當前對象進行加鎖)

若我們對如上代碼進行修改,在run()方法上加入synchronized關鍵字使其變為同步方法。

  1. /*
  2. * 同步方法
  3. * */
  4. class MyRunnable1 implements Runnable{
  5. private int num = 10;
  6. public void run() {
  7. this.print();
  8. }
  9.  
  10. public synchronized void print() {
  11. if(this.num > 0) {
  12. System.out.println(""+Thread.currentThread().getName()+"開始"+",num= "+num--);
  13. try {
  14. Thread.sleep(1000);
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. System.out.println(""+Thread.currentThread().getName()+"結束");
  19. }
  20. }
  21. }public class Test5_5{
  22. public static void main(String[] args) {
  23. MyRunnable1 myRunnable1 = new MyRunnable1();
  24. Thread thread1 = new Thread(myRunnable1,"線程1");
  25. Thread thread2 = new Thread(myRunnable1,"線程2");
  26. thread1.start();
  27. thread2.start();
  28. }
  29. }

利用synchronized實現線程同步的案例講解

結論:若兩個線程同時訪問同一個對象中的同步方法時一定是線程安全的。

(2)synchronized代碼塊(對某一個對象進行加鎖)

如果要使用同步代碼塊必須設置一個要鎖定的對象,所以一般可以鎖定當前對象:this.

  1. /*
  2. * 同步代碼塊
  3. * */
  4. class MyRunnable1 implements Runnable{
  5. private int num = 10;
  6. public void run() {
  7. try {
  8. synchronized (this) {
  9. if(num > 0) {
  10. System.out.println(""+Thread.currentThread().getName()+"開始"+",num= "+num--);
  11. Thread.sleep(1000);
  12. System.out.println(""+Thread.currentThread().getName()+"結束");
  13. }
  14. }
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. }
  20.  
  21. public class Test5_5{
  22. public static void main(String[] args) {
  23. MyRunnable1 myRunnable1 = new MyRunnable1();
  24. Thread thread1 = new Thread(myRunnable1,"線程1");
  25. Thread thread2 = new Thread(myRunnable1,"線程2");
  26. thread1.start();
  27. thread2.start();
  28. }
  29. }

利用synchronized實現線程同步的案例講解

(3)synchronized鎖多對象

  1. /*
  2. * synchronized鎖多對象
  3. * */
  4. class Sync{
  5. public synchronized void print() {
  6. System.out.println("print方法開始:"+Thread.currentThread().getName());
  7. try {
  8. Thread.sleep(1000);
  9. } catch (InterruptedException e) {
  10. // TODO Auto-generated catch block
  11. e.printStackTrace();
  12. }
  13. System.out.println("print方法結束"+Thread.currentThread().getName());
  14. }
  15. }
  16. class MyThread extends Thread{
  17. public void run() {
  18. Sync sync = new Sync();
  19. sync.print();
  20. }
  21. }
  22. public class Test5_5{
  23. public static void main(String[] args) {
  24. for(int i = 0; i < 3;i++) {
  25. Thread thread = new MyThread();
  26. thread.start();
  27. }
  28. }
  29. }

利用synchronized實現線程同步的案例講解

根據上例我們可以發現當synchronized鎖多個對象時不能實現同步操作,由此可以得出關鍵字synchronized取得的鎖都是對象鎖,而不是將一段代碼或者方法(函數)當作鎖。哪個線程先執行帶synchronized關鍵字的方法或synchronized代碼塊,哪個線程就有該方法或該代碼塊所持有的鎖,其他線程只能呈現等待狀態,前提是多個線程訪問同一個對象。

只有共享資源的讀寫需要同步化,如果不是共享資源,那么就不需要同步化操作。

3.全局鎖

實現全局鎖有兩種方式:

(1) 將synchronized關鍵字用在static方法上

synchronized加到static靜態方法上是對Class類上鎖,而synchronized加到非static方法上是給對對象上鎖。Class鎖可以對類的所有對象實例起作用。

  1. /*
  2. * synchronized用在static方法上
  3. * */
  4. class Sync{
  5. static public synchronized void print() {
  6. System.out.println("print方法開始:"+Thread.currentThread().getName());
  7. try {
  8. Thread.sleep(1000);
  9. } catch (InterruptedException e) {
  10. // TODO Auto-generated catch block
  11. e.printStackTrace();
  12. }
  13. System.out.println("print方法結束"+Thread.currentThread().getName());
  14. }
  15. }
  16. class MyThread extends Thread{
  17. public void run() {
  18. Sync.print();
  19. }
  20. }
  21. public class Test5_5{
  22. public static void main(String[] args) {
  23. for(int i = 0; i < 3;i++) {
  24. Thread thread = new MyThread();
  25. thread.start();
  26. }
  27. }
  28. }

利用synchronized實現線程同步的案例講解

(2) 用synchronized對類的Class對象進行上鎖

synchronized(class)代碼塊的作用與synchronized static方法的作用一樣。

  1. /*
  2. * synchronized對類的Class對象上鎖
  3. * */
  4. class Sync{
  5. public void print() {
  6. synchronized (Sync.class) {
  7. System.out.println("print方法開始:"+Thread.currentThread().getName());
  8. try {
  9. Thread.sleep(1000);
  10. } catch (InterruptedException e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. System.out.println("print方法結束"+Thread.currentThread().getName());
  15. }
  16. }
  17. }
  18. class MyThread extends Thread{
  19. public void run() {
  20. Sync sync = new Sync();
  21. sync.print();
  22. }
  23. }
  24. public class Test5_5{
  25. public static void main(String[] args) {
  26. for(int i = 0; i < 3;i++) {
  27. Thread thread = new MyThread();
  28. thread.start();
  29. }
  30. }
  31. }

利用synchronized實現線程同步的案例講解

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持我們。如有錯誤或未考慮完全的地方,望不吝賜教。

原文鏈接:https://blog.csdn.net/weixin_41101173/article/details/79705582

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日本无卡码一区二区三区 | 猛h辣h高h文湿校园1v1 | 2021国产精品成人免费视频 | 亚洲毛片基地 | 国产乱子伦在线观看不卡 | 日本大尺度动漫在线观看缘之空 | 男女男精品视频免费观看 | 亚洲福利一区二区三区 | 九九精品视频在线免费观看 | 91九色最新地址 | 精品午夜久久网成年网 | 91视频完整版 | 久久re视频这里精品一本到99 | 国产99区| 2020最新韩国理论三级0k | 国产亚洲精品一区二区在线观看 | 成人网视频免费播放 | 欧美一级特黄特色大片免费 | 丝瓜草莓香蕉绿巨人幸福宝 | 奶茶视频官网免费 | 欧美高清国产 | 欧洲第一页 | 日本人妖网站 | 欧美人与禽杂交大片 | 国产66 | 美女又爽又黄免费 | 亚洲精品国产精品麻豆99 | 爽好舒服把腿张小说 | 草久社区 | 视频在线观看一区二区 | 99久久伊人一区二区yy5099 | www视频免费观看 | 男人狂躁女人下半身 | 免费一级毛片完整版在线看 | 欧美一二 | 亚洲午夜天堂 | 日韩欧美在线看 | 狠狠综合视频精品播放 | 精品国产乱码久久久久久免费 | 欧美日韩中文字幕在线视频 | 成年女人毛片免费观看97 |