假设有火车票100张,创建10个线程模拟10个售票点,每个售票点随机生成时间卖一张票。 打印出售票过程,注意使用synchronized确保同一张票只能卖出一次。
import java.text.SimpleDateFormat;
import java.util.Date;
public class Resource {
int ticketNum;
boolean flag = false;
SimpleDateFormat sdf;
int i = 1;
public Resource(int ticketNum) {
this.ticketNum = ticketNum;
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
}
public synchronized void sellTicket(Seller s) {
if (i <= ticketNum) {
System.out.println("在" + sdf.format(new Date()) + " 第" + s.num
+ "售票点卖了第" + i + "张票...");
i++;
} else {
flag = true;
}
}
}
public class Seller implements Runnable {
int num;
Resource rs;
public Seller(int num, Resource rs) {
super();
this.num = num;
this.rs = rs;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (rs.flag == false) {
// 调用资源类的同步方法
rs.sellTicket(this);
try {
// 生成随机数(范围1-1000)
int random = (int) (Math.random() * 1000);
Thread.sleep(random);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource rs = new Resource(100);
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new Seller(i, rs));
t.start();
}
}
}