初级
package com
.lzy
.syn
;
public class dBookTrain {
public static void main(String
[] args
) {
Train t
=new Train("k1046",20);
new Thread(new Passenger(t
,5),"小明").start();
new Thread(new Passenger(t
,15),"小刚").start();
}
}
class Passenger implements Runnable{
Train train
;
int seats
;
public Passenger(Train train
, int seats
) {
this.train
= train
;
this.seats
= seats
;
}
@Override
public void run() {
synchronized(train
) {
boolean flag
=train
.choose(seats
);
if(flag
) {
System
.out
.println("欢迎乘坐"+train
.name
+"列车,"+Thread
.currentThread().getName()+"定了"+seats
+"张票");
}
else {
System
.out
.println("购票失败,请重试或选择其他列车");
}
}
}
}
class Train {
String name
;
int available
;
public Train(String name
, int available
) {
this.name
= name
;
this.available
= available
;
}
public boolean choose(int seats
) {
if(seats
>available
) {
return false;
}
available
-=seats
;
return true;
}
}
运行结果: 欢迎乘坐k1046列车,小明定了5张票 欢迎乘坐k1046列车,小刚定了15张票 在这只能显示乘客定了几张票,而不能清楚自己的位置在哪,下面代码稍微增进一下
增进代码(加入List)
package com
.lzy
.syn
;
import java
.util
.ArrayList
;
import java
.util
.List
;
public class dBookTrain02 {
public static void main(String
[] args
) {
List
<Integer> t
=new ArrayList<>();
for(int i
=1;i
<=10;i
++) {
t
.add(i
);
}
GoTrain g
=new GoTrain("k1046",t
);
List
<Integer> s
=new ArrayList<>();
s
.add(3);
s
.add(5);
List
<Integer>h
=new ArrayList<>();
h
.add(1);
h
.add(9);
h
.add(8);
h
.add(6);
new Thread(new GoPassenger(g
,s
),"lzy").start();
new Thread(new GoPassenger(g
,h
),"lll").start();
}
}
class GoPassenger implements Runnable{
GoTrain train
;
List
<Integer> seats
;
public GoPassenger(GoTrain train
, List
<Integer> seats
) {
this.train
= train
;
this.seats
= seats
;
}
@Override
public void run() {
synchronized(train
) {
boolean flag
=train
.choose(seats
);
if(flag
) {
System
.out
.println("欢迎乘坐"+train
.name
+"列车,"+Thread
.currentThread().getName()
+"定了"+seats
+"位置的票,"+"共"+seats
.size()+"张票");
}
else {
System
.out
.println("购票失败,请重试或选择其他列车");
}
}
}
}
class GoTrain {
String name
;
List
<Integer> available
;
public GoTrain(String name
, List
<Integer> available
) {
this.name
= name
;
this.available
= available
;
}
public boolean choose(List
<Integer> seats
) {
System
.out
.println("欢迎乘坐本班列车,本班列车可选位置有:"+available
);
List
<Integer> copyavailable
=new ArrayList<>();
copyavailable
.addAll(available
);
copyavailable
.removeAll(seats
);
if(available
.size()-copyavailable
.size()!=seats
.size()) {
return false;
}
available
=copyavailable
;
return true;
}
}
运行结果 欢迎乘坐本班列车,本班列车可选位置有:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 欢迎乘坐k1046列车,lzy定了[3, 5]位置的票,共2张票 欢迎乘坐本班列车,本班列车可选位置有:[1, 2, 4, 6, 7, 8, 9, 10] 欢迎乘坐k1046列车,lll定了[1, 9, 8, 6]位置的票,共4张票