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

    实验任务详情:

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

    1、实验代码

    package test;
    
    class MyThread implements Runnable{
    	
    		private int ticket = 1000;
    		
    		public void run() {
    			for(int i = 0; i < 1000; i++) {
    				   this.sale();
    				   if(i == Math.sqrt(i) * Math.sqrt(i)) {
    					   Thread.currentThread().yield();
    				   }
    				}
    			}
    		
    		 public synchronized void sale() {
    				if(ticket > 0) {
    					try {
    						Thread.currentThread().sleep(1000);
    					}catch(InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println(Thread.currentThread().getName()+"卖票:ticket="+ticket--);
    				}
    		 }
    }
    
    
    
    
    package test;
    
    public class Seven {
    	public static void main (String args[]) {
    		MyThread my = new MyThread();
    		for(int i = 1; i <= 10; i++) {
    			new Thread(my,"窗口"+i).start();
    		}	
    	}
    }
    
    
    


    学习总结

    线程操作的一些主要方法
    *public Thread(Runnable target) :接收Runnable 接口子类对象,实例化Thread对象。
    *public Thread(Runnable target, Stirng name) :接收Runnable 接口子类对象,实例化Thread对象,并设置线程名称。
    *public Thread (String name):实例化Thread对象,并且设置线程名称
    *public static Thread currentThread():返回目前正在执行的线程
    *public void start():开始执行线程

    线程的休眠:直接使用Thread.sleep()进行休眠

    线程的优先级:
    public static final int MIN_PRIORITY :最低优先级
    public static final int NORM_PRIORITY:中等优先级
    public static final int MAX_PRIORITY:最高优先级

    同步:多个操作在同一个时间段内只能有一个线程进行,其他线程要等待此线程完成后才可以继续执行
    同步代码块:
    synchronized(同步对象){
    需要同步的代码;
    }

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

  • 相关阅读:
    form表单的两种提交方式,submit和button的用法
    ORACLE SEQUENCE用法(转)
    hive优化
    Hive分区表创建、分类
    Hive体系结构
    Hive入门指南
    mysql统计表中条目个数的方法举例
    mysql如何快速创建相同结构的表
    VMware Workstation下VMnet1等虚拟网卡与主机网卡之间的关系
    linux命令详解——lsof
  • 原文地址:https://www.cnblogs.com/20188382llz/p/11734335.html
Copyright © 2011-2022 走看看