第九周课程总结&实验报告(七)

实验六

1)实验任务详情:

完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。

(一)实验代码:




package hlha;

	class MyThread implements Runnable{                  
	    private int ticket=1000;
	    public void run() {                                           
	        for(int i=0;i<100;i++) {
	            synchronized(this) {                            
	                if(ticket>0) {                                   
	                    try {
	                        Thread.sleep(1000);       
	                    }
	                    catch(InterruptedException e) {
	                        e.printStackTrace();
	                    }
	                    System.out.println(Thread.currentThread().getName()+"售票,余票:"+--ticket);    
	                }
	            }
	        }
	    }
	};
	public class shoupiao{
	    public static void main(String[] args) {
	         MyThread mt=new MyThread();       
	        for(int i=1;i<=10;i++) {           
	            new Thread(mt,"窗口"+i).start();
	        }
	    }
	}



运行结果:

学习总结:

一、实现多线程的方法

1、一种是继承Thread类;
继承Thread类多线程的定义语法:
class 类名称 extends Thread{
属性;
方法;
public void run(){
线程主体;
}
}
2、一种是实现Runnable接口。
通过Runnable接口实现多线程:
class 类名称 implements Runnable{
属性;
方法;
public void run(){
线程主体;
}
}

线程操作主要方法:

二、操作文件的类File
使用RandonAcccessFile类写入数据

原文地址:https://www.cnblogs.com/dapeng1234/p/11739863.html