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

实验任务详情:

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

实验代码

package 实验报告7;


	class MyThread implements Runnable{
		 private int ticket=1000;
		    public void run() { 
		        for(int i=0;i<1001;i++) {
		        
		        		this.sale();
		            }
		        }    
		    public synchronized void sale() {
		                if(ticket>0) {
		                  try {
		                      Thread.sleep(1000);
		                  }catch(Exception e) {
		                      e.printStackTrace();
		                  }
		                  System.out.println(Thread.currentThread().getName()+"售票,i="+ticket--);
		            }
		       }
		    }
package 实验报告7;



public class RunnableDemo02 {

	public static void main(String args[]){
	      MyThread mt=new MyThread();             
	        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();
	    }
}


本周实验 老师在上课的时候都讲过了的,基本上都没有什么问题。无论使用哪种方式,最终都必须依靠Thread才能启动多线程
还有主要是要区分Thread类和Runnable接口的区别,如果一个类继承Thread类,则不适合于多个线程共享资源,而实现了Runnable接口,就可以方便地实现资源共享。Thread类是Runnable接口地子类,而且
使用Runnable接口可以避免单继承局限,以及更加方便地实现数据共享。

原文地址:https://www.cnblogs.com/liualiu/p/11735437.html