資源簡介
簡單實現(xiàn)多線程同步示例(模擬購票系統(tǒng)),內(nèi)容為實現(xiàn)多線程同步過程,模擬購票系統(tǒng)進行同步購買情況;該處并未考慮線程守護問題,后期將對線程鎖等安全問題進行初步研究!

代碼片段和文件信息
package?cn.com.chysoft.demo2;
import?java.text.SimpleDateFormat;
/**
?*?線程實現(xiàn)
?*?
?*?@author?chenyong?QQ:369232566
?*?@date?2013-03-21?下午14:14
?*/
public?class?Instance?implements?Runnable?{
private?Ticket?ticket;
private?boolean?isOk;//?是否購票成功
private?TicketCentre?centre;//?票務(wù)中心
private?int?wtime;//?購票耗時
public?Instance(int?wtime?Ticket?ticket)?{
this.wtime?=?wtime;
this.ticket?=?ticket;
}
private?final?void?fun(int?wtime)?{
this.centre?=?ticket.getCentre();
try?{
this.isOk?=?this.centre.buy(this.ticket);//?購買
/**
?*?設(shè)置余票,因為對象中的數(shù)值是共享的
?*/
this.showMessage(this.ticket.getCentre().getSurplus());
Thread.sleep(wtime);
}?catch?(InterruptedException?e)?{
e.printStackTrace();
}
}
public?void?showMessage(int?current)?{
SimpleDateFormat?sdf?=?new?SimpleDateFormat(“yyyy-MM-dd?hh:mm:ss:SSSSSSS?-->?“);
StringBuffer?sbCtx?=?new?StringBuffer(sdf.format(this.ticket.getTime().getTime()));
sbCtx.append(this.ticket.getUser());
if?(this.isOk)?{
sbCtx.append(“?在?“).append(Thread.currentThread().getName()).append(“?購買?“).append(this.ticket.getNum()).append(“?張票?當(dāng)前剩余?“).append(current).append(“?張。“);
}?else?{
sbCtx.append(“?在?“).append(Thread.currentThread().getName()).append(“?購買失敗!“).append(“剩余?“).append(current).append(“?張。“);
}
System.out.println(sbCtx);
}
public?void?run()?{
this.fun(this.wtime);
}
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????1493??2013-03-21?14:18??demo2\Instance.java
?????文件???????1283??2013-03-21?14:18??demo2\main2.java
?????文件???????1000??2013-03-21?14:18??demo2\Ticket.java
?????文件???????1169??2013-03-21?14:18??demo2\TicketCentre.java
?????目錄??????????0??2013-03-21?11:25??demo2
-----------?---------??----------?-----??----
?????????????????4945????????????????????5
評論
共有 條評論