在編寫一個類時,如果該類中的代碼可能運行於多線程環境下,那麼就要考慮同步的問題。在Java中內建了語言級的同步原語--synchronized,這也大大簡化了Java中多線程同步的使用。 我們首先編寫一個非常簡單的多線程的程式,是類比銀行中的多個線程同時對同一個儲蓄賬戶進行存款、取款操作的。
在程式中我們使用了一個簡化版本的Account類,代表了一個銀行賬戶的資訊。在主程式中我們首先產生了1000個線程,然後啟動它們,每一個線程都對John的賬戶進行存100元,然後馬上又取出100元。這樣,對於John的賬戶來說,最終賬戶的餘額應該是還是1000元才對。然而啟動並執行結果卻超出我們的想像,首先來看看我們的示範代碼:
class Account
{
String name; float amount;
public Account(String name, float amount)
{
this.name = name;
this.amount = amount;
}
public void deposit(float amt)
{
float tmp = amount;
tmp += amt;
try
{
Thread.sleep(100);
//類比其它處理所需要的時間,比如重新整理資料庫等
}
catch (InterruptedException e)
{
// ignore
}
amount = tmp;
}
public void withdraw(float amt)
{
float tmp = amount;
tmp -= amt;
try
{
Thread.sleep(100);
//類比其它處理所需要的時間,比如重新整理資料庫等
}
catch (InterruptedException e)
{
// ignore
}
amount = tmp;
}
public float getBalance()
{
return amount;
}
}
public class AccountTest
{
private static int NUM_OF_THREAD = 1000;
static Thread[] threads = new Thread[NUM_OF_THREAD];
public static void main(String[] args)
{
final Account acc = new Account("John", 1000.0f);
for (int i = 0; i< NUM_OF_THREAD; i++)
{
threads[i] = new Thread(new Runnable()
{
public void run()
{
acc.deposit(100.0f);
acc.withdraw(100.0f);
}
}
);
threads[i].start();
}
for (int i=0; i<NUM_OF_THREAD; i++)
{
try { threads[i].join();
//等待所有線程運行結束
}
catch (InterruptedException e)
{
// ignore
}
}
System.out.println("Finally, John's balance is:" + acc.getBalance()); }}