实验任务详情:
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
实验代码:
package 实验七;
class MyThread implements Runnable{
private int ticket=1000;
public void run() {
for(int i=0;i<1000;i++) {
this.sell();
}
}
public synchronized void sell() {
if(ticket>0) {
try {
Thread.sleep(0);
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"售出:"+ticket--);
}
}
}
package 实验七;
public class Test {
public static void main(String[] args) {
MyThread win=new MyThread();
new Thread(win,"窗口A1").start();
new Thread(win,"窗口A2").start();
new Thread(win,"窗口A3").start();
new Thread(win,"窗口A4").start();
new Thread(win,"窗口A5").start();
new Thread(win,"窗口B1").start();
new Thread(win,"窗口B2").start();
new Thread(win,"窗口B3").start();
new Thread(win,"窗口B4").start();
new Thread(win,"窗口B5").start();
}
}
运行截图:随便截两张吧,结果太多
本周总结:
No.1 在Thread子类中,必须明确地覆写Thread类的run()方法。
No.2 实现Runnable接口,也要依靠Tread类完成,Tread类通过提供public Tread(Runnable target)和public Tread(Runnable target,String name)两种构造方法接受Runnable子类实例对象
No.3 Runnable可以避免单继承的局限,但是Runnable实现的多线程可能出现无法返回操作结果的情况
No.4 无论用哪种方式,最终都必须依靠Tread类才能启动多线程