zoukankan      html  css  js  c++  java
  • 第九周课程总结&实验报告(七)

    课程总结

    这周我们学习了多线程和一点点关于文件的输入与输出。

    线程

    线程共分为两大类 继承Thread 以及 实现Runnable接口。

    取得线程名称:Thread。curentThread().getNane()
    判断线程是否启动 isAlive();
    线程强制运行 join();
    后台线程 setDaemon();
                             最高级 MAX—PRIORITY
    线程的优先级   最高级 NORM—PRIORITY
                             最低级 MIN—PRIORITY
     线程的礼让 yield()
    

    同步代码块

    synchronized(同步对象){        ///synchronized(this)this表示当前对象
            需要同步的代码块;
    }
    

    同步方法

    synchronized  方法返回值  方法名称(参数列表){
            方法体
    }
    

    操作文件的类File

    使用RandonAcccessFile类写入数据

    实验报告

    实验任务详情:
    完成火车站售票程序的模拟。

    要求:

    (1)总票数1000张;
    (2)10个窗口同时开始卖票;
    (3)卖票过程延时1秒钟;
    (4)不能出现一票多卖或卖出负数号票的情况。
    代码

    实现Runnable接口类
    package test12;
    
    public class MyThread implements Runnable {
    	private int ticket = 1000;
    
    	public void run() {
    
    		for (int i = 1; i <= 1000; i++) {
    			synchronized (this) {
    				if(ticket==0) {
    					System.out.println(Thread.currentThread().getName() + "票已售完!");
    					break;
    				}
    				if (ticket > 0) {
    					ticket--;
    					try {
    						Thread.sleep(0);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println(Thread.currentThread().getName() + " 买出一张票    余票:ticket=" + ticket);
    
    				}
    			}
    		}
    
    	}
    };
    
    测试类
    package test12;
    
    public class Ceshi {
    
    	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();
    
    	}
    }
    

    运行截图



  • 相关阅读:
    ASP.NET Forms 身份验证概述
    JS中变量相关的细节分析
    document对象execCommand的命令参数介绍
    一点一点学ASP.NET之基础概念——HTTP运行期与页面执行模型
    读《大道至简》第一章有感
    读大道至简第二章有感
    课程作业2
    编写一个程序,用户输入两个数,求其加减乘除,并用消息框显示计算结果。
    201920201 20209324《Linux内核原理与分析》第一周作业
    jQuery Plugins
  • 原文地址:https://www.cnblogs.com/djhxxx/p/11734804.html
Copyright © 2011-2022 走看看