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

实验六

1)实验任务详情:

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

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

实验代码

    package 测试;

    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);    

                    }

                }

            }

        }

    };

          package 测试;

            public class 售{

                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(){

线程主体;

}

}

2.线程操作的主要方法

 

原文地址:https://www.cnblogs.com/wuming8510/p/11741196.html