【发布时间】:2015-08-28 07:42:31
【问题描述】:
takeAmount 和 addAmount 只是从 balanceAccount 中添加/子值(例如添加 11,12...,20 或添加 101,102...,110)。 balanceAccount 有两个版本,一个是使用同步功能,另一个是使用同步块。
BalanceAccount_synchronizedBlock 和 BalanceAccount_synchronizedFunction 有什么不同吗?
确实 BalanceAccount_synchronizedFunction 总是返回 0,而 BalanceAccount_synchronizedBlock 则不会。
而且...为什么它会表现出不同的行为?
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);
}
}
【问题讨论】:
-
它表现出什么不同的行为?
-
不要在
Integer上同步,因为它是不可变的,当amount被替换时,您将在不同的对象上同步,这可能会导致一些有趣的问题。您可以改用Object lock = new Object();进行同步。 -
感谢您的回复。它工作。
标签: java multithreading synchronization synchronized