班级 计科二班 学号 20188425 姓名 IM
完成时间2019/10/24
评分等级
实验任务详情:
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
实验代码
package 实验室; public class MyThread implements Runnable { private int ticket=1000; public void run() { for(int i=0;i<10000;i++) { this.sale1(); } } public synchronized void sale1() { if(ticket>0) { try { Thread.sleep(1000); }catch(InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"卖票:ticket="+ticket--); } } } package 实验室; public class ticket { public static void main(String args[]) { MyThread my=new MyThread(); Thread t1 = new Thread(my,"窗口A"); Thread t2 = new Thread(my,"窗口B"); Thread t3 = new Thread(my,"窗口C"); Thread t4 = new Thread(my,"窗口D"); Thread t5 = new Thread(my,"窗口E"); Thread t6 = new Thread(my,"窗口F"); Thread t7 = new Thread(my,"窗口G"); Thread t8 = new Thread(my,"窗口H"); Thread t9 = new Thread(my,"窗口I"); Thread t10 = new Thread(my,"窗口J"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); t8.start(); t9.start(); t10.start(); } }
运行结果截图:
实验总结:
这个编程还比较简单,就是用了一个同步代码块,结合书上的知识点即可解决。后续还需将此问题所需代码加以改进,更加智能化。
学习总结
学到了什么
Java IO
1.学习了IO包中的文件类,File类,其构造方法为:
public File(String pathname) → 实例化File类的时候,必须设置好路径。
创建一个新文件:
pakeage org.jeff.demo.filedemo; import java.io.File; import java.io IOException; public class File Demo01{ public static void main(String args[]){ File f = new File("d:\\test.txt"); try{ f.createNewFile(); }catch(IOException e){ e.printStackTrace(); } } }
Windows 中使用反斜杠表示目录的分隔符:“”。
Linux 中使用正斜杠表示目录的分隔符:“/”。
2.学习了RandomAccessFile类(随机读取)
使用rw(读写)的方式声明RandomAccessFile对象时,要写入的文件不存在,系统将自动创建。
学习不足
不能举一反三,仅能依葫芦画瓢。
不能完全自主闭卷完成作业
学习改进:
保持独立思考的习惯
反复写一个类型的代码,直到完全弄懂此类代码。