zoukankan      html  css  js  c++  java
  • JAVA多线程售票问题

    //定义一个类实现Runnable接口,定义一个需要同步的售票方法,然后重写run方法调用售票的sale方法

    [java] view plain copy
     

        1. class SaleTicket implements Runnable{  
        2.     private int tickets = 100;  
        3.       
        4.       
        5.     private synchronized void sale(){  
        6.         if(tickets > 0){  
        7.             System.out.println(Thread.currentThread().getName() + "卖出 第 "+ (tickets--)+"张票");  
        8.               
        9.             try{  
        10.                 Thread.sleep(100);  
        11.             }catch(InterruptedException e){  
        12.                 e.printStackTrace();  
        13.             }  
        14.         }  
        15.     }  
        16.     public void run(){  
        17.         while(tickets > 0){  
        18.             sale();  
        19.         }  
        20.     }  
        21. }  
        22.   
        23.   
        24. public class JavaTest {  
        25.           
        26.     public static void main(String[] args){  
        27.   
        28.   
        29.         SaleTicket st = new SaleTicket();  
        30.         Thread t1 = new Thread(st, "一号窗口");  
        31.         Thread t2 = new Thread(st, "二号窗口");  
        32.         Thread t3 = new Thread(st, "三号窗口");  
        33.         Thread t4 = new Thread(st,"四号窗口 ");  
        34.         t1.start();  
        35.         t2.start();  
        36.         t3.start();  
        37.         t4.start();  
        38.           
        39.       
        40.           
        41.     }  
        42. }  
  • 相关阅读:
    调试常用命令
    android获取手机机型、厂商、deviceID基本信息
    融云即时通讯 添加地理位置信息的功能
    Linux centOS下搭建RTMP服务器的具体步骤
    数组与字符串 1.4
    数组与字符串 1.5
    数组与字符串 1.3
    数组与字符串 1.2
    数组与字符串 1.1
    笔记本自开wifi设置
  • 原文地址:https://www.cnblogs.com/DIMON/p/5265794.html
Copyright © 2011-2022 走看看