多线程共享数据问题

2017-08-13  本文已影响0人  jose_dl

经典卖票例子

package com.cskaoyan.a;

public class Test3 {
    
    public static void main(String[] args) {
        
        SellTicket sTicket = new SellTicket();
        Thread t1 = new Thread(sTicket);
        Thread t2 = new Thread(sTicket);
        Thread t3 = new Thread(sTicket);
        
        t1.start();
        t2.start();
        t3.start();
    }

}
class SellTicket implements Runnable{
    int tickets=100;

    @Override
    public void run() {

        while (true&&tickets>0) {
            System.out.println(Thread.currentThread().getName()+"卖出了一张,剩余"+(--tickets));
        }
    }
    
}
    while(true){
            //线程共享数据,保证安全,加入同步代码块
            synchronized(obj){
            //对票数判断,大于0,可以出售,变量--操作
                if( ticket > 0){
                    try{
                       Thread.sleep(10);
                    }catch(Exception ex){}
                    System.out.println(Thread.currentThread().getName()+" 出售第 "+ticket--);
                }
            }
        }
public  synchronized void payTicket(){  
            if( ticket > 0){
                try{
                   Thread.sleep(10);
                }catch(Exception ex){}
                System.out.println(Thread.currentThread().getName()+" 出售第 "+ticket--);
            }
        
    }
上一篇下一篇

猜你喜欢

热点阅读