首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 每日一題:多執行緒同步輸出順序分析(20170308)

     編輯:Java 相關知識

題目代碼

public class Ques0308 implements Runnable {
    private String str1 = "this ";
    private int[] str2 = {1,2,3,4,5};

    public static void main(String[] args) {
        Ques0308 test = new Ques0308();
        new Thread(test).start();
        new Thread(test).start();
    }

    @Override
    public synchronized void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(str1 + str2[i]);
        }
    }
}

問題

請分析主程式運行輸出結果。

解析

  1. 兩個 Thread 共用同一個 Runnable 實例 (test)。
  2. run() 方法加了 synchronized,鎖對象是 test 實例。
  3. 因此兩個執行緒**互斥執行** run(),不會交錯輸出。
  4. 先搶到鎖的執行緒完整印出 5 行,釋放鎖後第二個執行緒再印 5 行。

輸出結果 (順序不定,但每組連續)

this 1
this 2
this 3
this 4
this 5
this 1
this 2
this 3
this 4
this 5

或相反順序 (取決於執行緒調度)。

關鍵點

  • synchronized 實例方法鎖住 this (即共用的 Runnable 實例)。
  • 若 run() 不加同步,則會交錯輸出。
  • 若建立兩個 new Ques0308(),則鎖不同,會交錯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved