public class MythreadM {
public static void main(String[] args) {
// TODO Auto-generated method stub
Msg m = new Msg();
Mythread thread1 = new Mythread(m);
thread1.start();
Mythread thread2 = new Mythread(m);
thread2.start();
Mythread thread3 = new Mythread(m);
thread3.start();
}
}
class Mythread extends Thread
{
private Msg m;
Mythread(Msg m)
{
this.m = m;
}
public void run()
{
System.out.println(getName() "start");
for(int i=0; i<300; i )
{
processMsg(i);
}
}
synchronized void processMsg(int i) // here starts question.
{
// synchronized(m)
{
m.write(getName() " message " i);
try {
sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.print();
}
}
}
class Msg
{
String str = "def message";
void print()
{
System.out.println(str " " System.currentTimeMillis());
}
void write(String str)
{
this.str = str;
}
}
上面的完整代碼-----------------
并遵循具有幾乎相同運算式的 3 個代碼。
<< 代碼 1 >> : 同步(m) {}
void processMsg(int i)
{
synchronized(m)
{
m.write(getName() " message " i);
try {
sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.print();
}
}
<< 代碼 2 >> : 同步 void processMsg(int i)
synchronized void processMsg(int i)
{
{
m.write(getName() " message " i);
try {
sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.print();
}
}
<< code 3 >> : synchronized void processMsg(int i) without inner{}
synchronized void processMsg(int i)
{
m.write(getName() " message " i);
try {
sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.print();
}
看起來這 3 個代碼的含義相同,只是表達方式不同,但這 3 個代碼的行為完全不同。
甚至 <code 2> 不同步,列印非同步結果。
為什么會這樣?
的目的是sleep(1);什么?
提前致謝。
uj5u.com熱心網友回復:
"Even < code 2 > is not synchronized, prints non-synchronized results. Why is this happening?"
當您在 上同步時m,它是一個實體變數。每個MyThread都有自己的副本。因此它基本上根本不同步,因為每個執行緒總是可以獲取鎖。
穿上synchronized方法也是如此processingMsg()。這是您制作的三個單獨的物件,并且只有物件是同步的。如果你想讓三個物件共享一個鎖,你需要一個靜態鎖或類似的東西。
uj5u.com熱心網友回復:
看起來這是示例代碼,用于演示當對所有執行緒 (m) 共有的物件進行同步時,一次只有一個執行緒可以使用它,而不是在執行緒中同步方法時,這不起作用任何事情,因為每個執行緒都獲得了自己的鎖。
對于您的第二個問題, sleep(1) 的含義是當前執行緒應該在繼續之前等待至少1 毫秒。
最后,根據我的經驗,當您有多個執行緒在同一資源之后(尤其是像 System.out 這樣的(列印)流),解決此問題的最佳方法是使用訊息佇列來同步發出的訊息。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477526.html
上一篇:如何在Java中正確使用條件?
下一篇:過濾器陣列包含多個專案
