多线程-初识并发-例子抢票


package Threads;

//实现多个线程,操作同一个实现类

//问题:多个线程同时操作一个资源的情况下,线程不安全了,数据紊乱
public class testRable implements Runnable {
    //票数
   private int ticketNums=100;
   
    public void run(){
    while(true){
        if (ticketNums>=0){ 
            //模拟延时
            try{
                Thread.sleep(200);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        System.out.println(Thread.currentThread().getName()+"拿到了第:"+ticketNums--+"");//先拿到票再减减
    }else{
        
        break;
        
    }         
        }
    }
    public static void main(String []args){
        //创建线程实现类对象
        testRable t1=new testRable();
        //创建线程对象,并启三个线程把实现类对象添加到线程,然后为线程命名
        Thread ead1=new Thread(t1,"线程1"); 
        Thread ead2=new Thread(t1,"线程2"); 
        Thread ead3=new Thread(t1,"线程3"); 
        
        
        //启动线程
        ead1.start();
        ead2.start();
        ead3.start();
        
        
}
    
    
}

相关