10/20-10/26 java学习总结(没有课堂的课后学习总结) &实验总结7
实验报告Ⅶ
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
package Love; class hope implements Runnable { static int tick = 1000; public void run() { for(int i=0;i<100;i++) { synchronized(this) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (tick > 0) { System.out.println(Thread.currentThread().getName() + "售票成功,车票号为" + tick); tick--; } else { System.out.println("不好意思,票已售完!"); }+ } } } }; public class name { public static void main(String[] args) { hope mt = new hope(); new Thread(mt,"窗口1").start(); new Thread(mt,"窗口2").start(); new Thread(mt,"窗口3").start(); new Thread(mt,"窗口4").start(); new Thread(mt,"窗口5").start(); new Thread(mt,"窗口6").start(); new Thread(mt,"窗口7").start(); new Thread(mt,"窗口8").start(); new Thread(mt,"窗口9").start(); new Thread(mt,"窗口10").start(); } }
一开始虽然看起来运行时对的,但是想起来老师上课说的要多线程同步或者线程锁来防止数据无法传到终端的情况(一票多卖等情况)的发生,所以加了个接口,进行了多线程同步。
错误截图
课堂总结
通过Runnable接口创建线程的步骤如下:
1、定义实现Runnable接口的类,并实现该类中的run()方法。
2、建立一个Thread对象,并将实现的Runnable接口的类的对象作为参数传入Thread类的构造方法。
3、通过Thread类中的start()方法启动线程。
1、定义实现Runnable接口的类,并实现该类中的run()方法。
2、建立一个Thread对象,并将实现的Runnable接口的类的对象作为参数传入Thread类的构造方法。
3、通过Thread类中的start()方法启动线程。
实现Runnable接口相对于继承Thread类的优势
1.避免了继承Thread类的单继承的局限性。
2.Runable接口出现更符合面向对象,将线程单独进行对象的封装。
3.Runnable接口出现,降低了线程对象和线程任务的耦合性。所以创建线程的方式都使用Runnable接口。
Java IO
操作文件的类——File
在整个IO包中,唯一表示与文件本身有关的类就是File类,使用file类可以进行创建或删除文件等常用操作。
序号 | 方法或常量 | 类型 | 描述 |
---|---|---|---|
1 | public static final String pathSeparator | 常量 | 表示路径的分隔符(windows 是:";") |
2 | public final String separator | 常量 | 表示路径的分隔符(windows 是:"") |
3 | public File(String pathname) | 构造 | 创建File类对象,传入完整路径 |
4 | public File(File parent,String child) | 构造 | 根据指定的父路径创建子文件 |
5 | public boolean createNewFile() throws IOException | 普通 | 创建新文件 |
6 | public boolean delete() | 普通 | 删除文件 |
7 | public boolean exists() | 普通 | 判断文件是否存在 |
8 | public boolean isDirectory() | 普通 | 判断给定的路径是否是一个目录 |
9 | public long length() | 普通 | 返回文件的大小 |
10 | public String[] list() | 普通 | 列出指定目录的全部内容,只是列出了名称 |
11 | public File[] listFiles() | 普通 | 列出指定目录的全部内容,会列出路径 |
12 | public boolean mkdir() | 普通 | 创建一个目录 |
13 | public boolean mkdirs() | 普通 | 创建多级目录 |
14 | public boolean renameTo(File dest) | 普通 | 为已有的文件重新命名 |
15 | public long lastModified | 普通 | 取得文件的最后一次修改日期时间 |
16 | public File getParentFile() | 普通 | 取得当前路径的父路径 |