(1)加深對進程併發執行的理解,認識多進程併發執行的實質。java
(2)觀察進程共享資源的現象,學習解決進程互斥和同步的方法。算法
本實驗要求用高級語言,啓動多進程併發運行,設計相應代碼,顯示進程無關併發、進程共享變量併發的運行結果。並完成實驗報告。併發
3、實驗內容:ide
分別實現如下四種狀況的併發:學習
1.併發的進程之間無關,顯示進程名稱,開始與結束時間。this
模擬多終端售票狀況,併發的多個終端進程之間共享剩餘票數這個共享變量。spa
2.用全局變量實現。線程
3.用進程間共享數據機制實現。設計
4.用進程間共享數據機制和加鎖機制實現。code
4、實驗過程與結果
public
class
SellTicket
implements
Runnable{
public
static
void
main(String[] agrs){
Object A =
"A"
;
//對象A的鎖
Object B =
"B"
;
//對象B的鎖
Object C =
"C"
;
SellTicket sA =
new
SellTicket(C,A);
SellTicket sB =
new
SellTicket(A,B);
SellTicket sC =
new
SellTicket(B,C);
Thread tA =
new
Thread(sA,
"A線程"
);
Thread tB =
new
Thread(sB,
"B線程"
);
Thread tC =
new
Thread(sC,
"C線程"
);
tA.start();
try
{
Thread.sleep(
100
);
}
catch
(InterruptedException e){
e.printStackTrace();
}
tB.start();
try
{
Thread.sleep(
100
);
}
catch
(InterruptedException e){
e.printStackTrace();
}
tC.start();
try
{
Thread.sleep(
10000
);
}
catch
(InterruptedException e){
e.printStackTrace();
}
synchronized
(B){
B.notify();
}
}
public
static
int
count =
10
;
//全局票數
public
volatile
boolean
why =
true
;
private
Object prev;
private
Object self;
public
SellTicket(Object prev,Object self){
this
.prev = prev;
this
.self = self;
}
@Override
public
void
run(){
while
(print());
}
private
boolean
print(){
while
(count >
0
){
synchronized
(prev) {
synchronized
(self){
System.out.println(Thread.currentThread().getName() + "賣出第:" + count-- + "張,剩餘"+count+"張");
count --;
System.out.println(Thread.currentThread().getName()+ self +
".notify"
);
self.notify();
}
if
(!(count==
0
)){
try
{
System.out.println(Thread.currentThread().getName() + prev +
".wait"
);
prev.wait();
}
catch
(InterruptedException e){
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName()+"return true");
return
true
;
}
System.out.println(Thread.currentThread().getName()+"return false");
return
false
;
}
}