同步處理 Synchronized
範例題目
完整程式碼(未經同步處理)
class CDonate
{
private static int sum=0;
public static void add(int n)
{
int tmp=sum;
tmp=tmp+n;
try
{
Thread.sleep((int)(1000*Math.random()));
}
catch(InterruptedException e){}
sum=tmp;
System.out.println("捐款總額= "+sum);
}
}
class CPerson extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
CDonate.add(100);
}
}
public class synchronized_1
{
public static void main(String args[])
{
CPerson p1=new CPerson();
CPerson p2=new CPerson();
p1.start();
p2.start();
}
}

完整範例程式碼(經同步處理)
Last updated