[英]What is the difference between synchronized(this) and synchronized method
[英]Want a code for the difference between synchronized and asynchronized method
我試圖設置同步和非同步方法之間的區別..我試過以下代碼
class Counter {
private int counter = 10;
public int getCounter() {
return counter;
}
public synchronized void doIncrementAndDecrement() {
counter++;
keepBusy(500);
counter--;
}
public void keepBusy(int howLong) { // (D)
long curr = System.currentTimeMillis();
while (System.currentTimeMillis() < curr + howLong)
;
}
}
class MyCounterThread extends Thread {
Counter c;
public MyCounterThread(Counter c, String name) {
// TODO Auto-generated constructor stub
super(name);
this.c = c;
start();
}
@Override
public void run() {
for (;;) {
c.doIncrementAndDecrement();
sleepForSometime();
System.out.println(c.getCounter());
}
}
public void sleepForSometime() { // (D)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class UnSynchronizedExapmle {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
MyCounterThread t1 = new MyCounterThread(c, "A");
MyCounterThread t2 = new MyCounterThread(c, "B");
MyCounterThread t3 = new MyCounterThread(c, "C");
}
}
所以上面我有doIncrementAndDecrement()同步方法..
所以我期望計數器的價值每次都應該是10。 但這不會發生我有輸出就好
10
10
11
10
10
10
10
11
10
10
11
10
11
11
10
10
11
10
11
10
10
10
11
10
10
11
10
所以請幫助我為什么會發生這種情況..或任何博客/文章解釋同步和異步方法之間的區別
您的getCounter()方法未同步。 因此,即使一個線程可能正在鎖定該方法,另一個線程仍然可以訪問並打印您的計數器變量
您的代碼不會同步getCounter方法,以便System.out.println可以輸出計數器的內部。 作為同步(本)上同步方法是相同。
...如果我在keepBusy()方法中編寫Thread.sleep(),它會有什么不同...因為輸出在兩種情況下都是完全不同的。
它的作用是使keepBusy()
花費很長時間,因此它使getCounter()
等待很長時間。
輸出的差異是由於同步阻止了getCounter()
在增量狀態下“看到”計數器。
我的意思是什么區別使得Thread.sleep()和keepBusy()方法中的上述while循環在線程調度或鎖定方面做出了貢獻。
這沒什么區別。
對於記錄,真正的程序有一個像keepBusy()
睡眠在同步方法或塊中的方法是keepBusy()
。 sleep
導致嘗試在目標對象上同步的任何其他線程被阻止......並且這可能會降低應用程序的實際並行度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.