takeAmount和addAmount僅僅是從balanceAccount添加/子值(例如,添加11,12 ...,20或添加101,102 ...,110)。 balanceAccount有兩個版本,一個是使用synchronized函數,另一個是使用synchronized塊。Java同步函數工作,同步塊不工作
BalanceAccount_synchronizedBlock和BalanceAccount_synchronizedFunction之間有什麼不同嗎?
確實BalanceAccount_synchronizedFunction始終返回0,而BalanceAccount_synchronizedBlock不會。
And ...爲什麼它會顯示不同的行爲?
public class mainStart {
public static void main(String args[])
{
for (int i=1;i<3000;i=i+10)
{
new Thread(new addAmount(i)).start();
new Thread(new takeAmount(i)).start();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//BalanceAccount_synchronizedBlock.printAmount();
BalanceAccount_synchronizedFunction.printAmount();
}
}
class takeAmount implements Runnable {
private int startFrom;
public takeAmount(int start)
{
this.startFrom=start;
}
public void run()
{
for (int i=startFrom;i<startFrom+10;i++)
//BalanceAccount_synchronizedBlock.sub(i);
BalanceAccount_synchronizedFunction.sub(i);
}
}
class addAmount implements Runnable {
private int startFrom;
public addAmount(int start)
{
this.startFrom=start;
}
public void run()
{
for (int i=startFrom;i<startFrom+10;i++)
//BalanceAccount_synchronizedBlock.add(i);
BalanceAccount_synchronizedFunction.add(i);
}
}
public class BalanceAccount_synchronizedBlock {
public static Integer amount=0;
public static void add(int a)
{
synchronized (amount)
{
amount = amount + a;
}
}
public static void sub(int a)
{
synchronized (amount)
{
amount = amount - a;
}
}
public synchronized static void printAmount()
{
System.out.println("Amount " + amount);
}
}
public class BalanceAccount_synchronizedFunction {
public static Integer amount=0;
public synchronized static void add(int a)
{
amount = amount + a;
}
public synchronized static void sub(int a)
{
amount = amount - a;
}
public synchronized static void printAmount()
{
System.out.println("Amount " + amount);
}
}
它顯示了什麼不同的行爲? – RealSkeptic
不要在'Integer'上同步,因爲它是不可變的,當'amount'被替換時,你會在不同的對象上同步,這會導致有趣的問題。你可以使用'Object lock = new Object();'來代替同步。 – Kayaman
感謝您的回覆。這行得通。 – user2602196