Exercise thread - buy tickets Network

Package cn.BuyTickets;
 // thread class 
public  class BuyTickets the implements the Runnable {
     Private  int NUM;
     Private  int COUNT = 10 ; 
    
    @Override 
    public  void RUN () {
         the while ( to true ) {
             Boolean In Flag = Buy ();
             IF (In Flag == false ) {
                 return ; 
            } 
        } 
        
    } 
    // synchronized not be placed in the run method, otherwise only one person to grab votes 
    synchronized public boolean buy() {
        if(count==0) {
            System.out.println("已无票");
            return false;
        }
        num++;
        count--;
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"抢到了第"+num+"张票,余票"+count+"张");
        if("黄牛党".equals(Thread.currentThread().getName())){
            return false;    
        }
        return true;
    }        
}
线程类
package cn.BuyTickets;

public class Main {
    public static void main(String[] args) {
        BuyTickets bt = new BuyTickets();
        Thread d1 = new Thread(bt,"淘泡泡");
        Thread d2 = new Thread(bt,"张票票");
        Thread d3 = new Thread(bt,"黄牛党");
        d1.start();
        d2.start();
        d3.start();
        
    }
}
main方法类

 

Guess you like

Origin www.cnblogs.com/lev1/p/11305833.html