代码改变世界

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

2019-10-25 16:59  小小乌龟君  阅读(172)  评论(1编辑  收藏  举报

本周内容

(1)多个线程访问同一资源时,考虑数据操作的安全性问题,一定要使用同步操作。同步有以下
两种操作模式:
① 同步代码块:synchronized(锁定对象)(代码)
② 同步方法:public syncbronized 返回值 方法名称(){代码}
(2)过多的同步操作有可能会带来死锁问题,导致程序进入到停带状态。

完成火车站售票程序的模拟。

要求:

(1)总票数1000张;

(2)10个窗口同时开始卖票;

(3)卖票过程延时1秒钟;

(4)不能出现一票多卖或卖出负数号票的情况。

 class MyThread implements Runnable{

	 private int ticket = 1000;
	 
	 public void run() {
		 
		 for(int i=0;i<1000;i++) {
			 
			 synchronized(this) {
				 if(ticket>0) {
					 try {
	                     Thread.sleep(0);
	                 } catch (InterruptedException e) {
	                     e.printStackTrace();
	                 }
					 System.out.println(Thread.currentThread().getName()+" 已售出一张  剩余票数"+ticket--);
				 }
				 if(ticket==0) {
					 System.out.println(Thread.currentThread().getName()+"  余票不足");
					 break;
				 }
			 }
		 }
	 }
}
public class maipiao {
	public static void main(String[] args) {
		MyThread my = new MyThread();
		Thread t1=new Thread(my,"窗口1");
        Thread t2=new Thread(my,"窗口2");
        Thread t3=new Thread(my,"窗口3");
        Thread t4=new Thread(my,"窗口4");
        Thread t5=new Thread(my,"窗口5");
        Thread t6=new Thread(my,"窗口6");
        Thread t7=new Thread(my,"窗口7");
        Thread t8=new Thread(my,"窗口8");
        Thread t9=new Thread(my,"窗口9");
        Thread t10=new Thread(my,"窗口10");
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        t9.start();
        t10.start();
		
	}

}