我對於同步塊有疑問。執行下面的代碼後I M geeting輸出爲:線程:同步塊
Inside run=>thread 2
Inside run=>thread 1
Inside run=>thread 1
Inside run=>thread 2
Inside run=>thread 2
Inside run=>thread 1
Inside run=>thread 2
Inside run=>thread 1
Inside run=>thread 1
Inside run=>thread 2
我期待輸出只有一個線程將首先執行同步塊,然後只第二線程將得到synchornized塊的訪問。 可能是我理解錯誤的概念?
package com.blt;
public class ThreadExample implements Runnable {
public static void main(String args[])
{
System.out.println("A");
Thread T=new Thread(new ThreadExample());
Thread T1=new Thread(new ThreadExample());
System.out.println("B");
T.setName("thread 1");
T1.setName("thread 2");
System.out.println("C");
T.start();
System.out.println("D");
T1.start();
}
synchronized public void run()
{
for(int i=0; i<5; i++)
{
try
{
System.out.println("Inside run=>"+Thread.currentThread().getName());
Thread.currentThread().sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
嘗試僅實例化一個ThreadExample,並將同一實例傳遞給線程T和線程T1的構造函數,原因是人們已經提供了答案中所述的原因。 – Alderath 2013-02-11 10:18:17