zoukankan      html  css  js  c++  java
  • Java---多线程售票

    package day;
    
    public class Mytd implements Runnable {         //通过实现Runnable接口来实现多线程
        private int ticketcount = 100;
        Object ob = new Object();                  //加锁
        private int m = 100;
    
        public Mytd(int t) {                       //有参构造方法
            this.ticketcount = t;
            this.m = t;
        }
    
        public Mytd() {                           //无参构造方法
    
        }
    
        public void sellticket() {                //卖票方法
           synchronized (ob) {                    //同步线程锁
                if (ticketcount > 0) {
                    ticketcount--;
                    int num = this.m - ticketcount;
                    System.out.println(Thread.currentThread().getName()
                            + "卖出第" + num + "张票,还剩" + ticketcount + "张票");
                } else {
                    System.out.println("票已经卖完");
                    return;
                }
           }
        }
    
        @Override
        public void run() {
            while (ticketcount > 0) {
                sellticket();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    package day;
    
    public class Work {
        public static void main(String[] args) {
            Mytd run = new Mytd(100);
            Thread th1 = new Thread(run,"东风路售票点");           //开启五个线程
            Thread th2 = new Thread(run,"吉祥路售票点");
            Thread th3 = new Thread(run,"从动路售票点");
            Thread th4 = new Thread(run,"文明路售票点");
            Thread th5 = new Thread(run,"好听路售票点");
            th1.start();
            th2.start();
            th3.start();
            th4.start();
            th5.start();
        }
    }
    
    
    
     
  • 相关阅读:
    WPF项目学习.一
    AtCoder Beginner Contest 210 A~D 题解
    P7715 「EZEC-10」Shape 题解
    P6216 回文匹配 题解
    字符串学习笔记
    #2742. 「JOI Open 2016」销售基因链
    树状数组学习笔记
    2021 省选游记
    AtCoder Beginner Contest 196 E
    AtCoder Regular Contest 113 A~D题解
  • 原文地址:https://www.cnblogs.com/zxwen/p/9673227.html
Copyright © 2011-2022 走看看