//不安全的卖票的改进//线程不安全有负数publicclassUnsafeBuyTicket{publicstaticvoidmain(String[] args){BuyTicket station =newBuyTicket();newThread(station,"我").start();newThread(station,"你们").start();newThread(station,"黄牛").start();}}classBuyTicketimplementsRunnable{// 票privateint ticketNums =10;boolean flag =true;@Overridepublicvoidrun(){//买票while(flag){buy();}}// synchronized同步方法privatesynchronizedvoidbuy(){//判断是否有票if(ticketNums<=0){
flag =false;return;}//模拟延时try{Thread.sleep(100);}catch(InterruptedException e){
e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");}}
//线程不安全的集合的改进publicclassUnsafeList{publicstaticvoidmain(String[] args){List<String> list =newArrayList<String>();//使用lambda表达式for(int i =0; i <10000; i++){newThread(()->{synchronized(list){
list.add(Thread.currentThread().getName());}}).start();}try{Thread.sleep(100);}catch(InterruptedException e){
e.printStackTrace();}System.out.println(list.size());}}
买票问题//不安全的卖票的改进//线程不安全有负数public class UnsafeBuyTicket { public static void main(String[] args) { BuyTicket station = new BuyTicket(); new Thread(station,"我").start(); new Thread(station,"你们").start(); new Thread(stati