生成随机数模拟售票,学习多线程
最近应用开发的程过中出现了一个小问题,顺便记录一下原因和方法--生成随机数
假设有火车票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();
}
}
}
文章结束给大家分享下程序员的一些笑话语录: 很多所谓的牛人也不过如此,离开了你,微软还是微软,Google还是Google,苹果还是苹果,暴雪还是暴雪,而这些牛人离开了公司,自己什么都不是。

浙公网安备 33010602011771号