/**
* <p>Title: 線程同步</p>
* <p>Description: 通過使用同步鎖實現對共享數據的操作</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: SyThreadDemo.java</p>
* @version 1.0
*/
/**
*<br>類說明:主程序
*<br>功能描述:構造兩個線程,並啟動它們
*/
public class SyThreadDemo
{
public static void main (String [] args)
{
trade ft = new trade ();
addThread tt1 = new addThread (ft, "add");
decThread tt2 = new decThread (ft, "dec");
tt1.start ();
tt2.start ();
}
}
/**
*<br>類說明:同步類
*<br>功能描述:保存共享數據,
*/
class trade
{
private String transName;
private double amount;
/**
*<br>方法說明:更新數據
*<br>輸入參數:String transName 操作名稱
*<br>輸入參數:double amount 資金數量
*<br>返回類型:
*/
synchronized void update (String transName, double amount)
{
this.transName = transName;
this.amount = amount;
System.out.println (this.transName + " " + this.amount);
}
}
/**
*<br>類說明:添加資金
*<br>功能描述:單線程,調用trade.update()方法,修改數據
*/
class addThread extends Thread
{
private trade ft;
addThread (trade ft, String name)
{
super (name);
this.ft = ft;
}
public void run ()
{
for (int i = 0; i < 10; i++)
ft.update ("add", 2000.0);
}
}
/**
*<br>類說明:減少資金
*<br>功能描述:單線程,調用trade.update()方法,修改數據
*/
class decThread extends Thread
{
private trade fd;
decThread (trade fd, String name)
{
super (name);
this.fd = fd;
}
/**
*<br>方法說明:線程主體
*<br>輸入參數:
*<br>返回類型:
*/
public void run ()
{
for (int i = 0; i < 10; i++)
fd.update ("dec", -2000.0);
}
}