实验任务详情:
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
1.实验源码
class MyThread implements Runnable{
private int ticket = 1000;
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
synchronized (this){
if (ticket>0){
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票:ticket="+ticket--);
}
}
}
}
}
public class sell {
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread t1=new Thread(mt,"窗口1");
Thread t2=new Thread(mt,"窗口2");
Thread t3=new Thread(mt,"窗口3");
Thread t4=new Thread(mt,"窗口4");
Thread t5=new Thread(mt,"窗口5");
Thread t6=new Thread(mt,"窗口6");
Thread t7=new Thread(mt,"窗口7");
Thread t8=new Thread(mt,"窗口8");
Thread t9=new Thread(mt,"窗口9");
Thread t10=new Thread(mt,"窗口10");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}
2.实验结果截图
3.实验过程
上课听了老师所讲的,以及加上看书上了,懂了synchronized();同步代码块的使用
4.本周学习小结
1.将本周老师所重点讲的代码自己复现了一遍
2.至于总结,周日添加。。。未完待续
5.改进后:
一、实验源码
package housewor;
public class MyThread implements Runnable {
private int ticket = 1000;
@Override
public void run() {
while (true) {
synchronized (this) {//同步代码块 保证不卖出重复票 一票多卖
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "窗口:卖出了第" + ticket + "张票!");
ticket--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
break;
}
}
}
}
}
public class Run {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt,"A").start();
new Thread(mt,"B").start();
new Thread(mt,"C").start();
new Thread(mt,"D").start();
new Thread(mt,"E").start();
new Thread(mt,"F").start();
new Thread(mt,"G").start();
new Thread(mt,"H").start();
new Thread(mt,"I").start();
new Thread(mt,"G").start();
}
}
二、实验结果截图
三、改进后
1.代码比之前的清楚,并且没有那么多乱七八糟的东西了
2.售票没有问题了