publicclassUnsafeBuyTickets{ publicstaticvoidmain(String[] args){ Buytickets station = new Buytickets(); new Thread(station,"小明").start(); new Thread(station,"小红").start(); new Thread(station,"黄牛").start(); }
}
classBuyticketsimplementsRunnable{ privateint ticketNum = 10; boolean flag = true; @Override publicvoidrun(){ while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } publicvoidbuy()throws InterruptedException { if (this.ticketNum<=0){ flag = false; return ; } Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"买到了"+ticketNum--); } }
publicclassUnsafeBuyTickets{ publicstaticvoidmain(String[] args){ Buytickets station = new Buytickets(); new Thread(station,"小明").start(); new Thread(station,"小红").start(); new Thread(station,"黄牛").start(); }
}
classBuyticketsimplementsRunnable{ privateint ticketNum = 10; boolean flag = true; @Override publicvoidrun(){ while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } publicvoidbuy()throws InterruptedException { if (this.ticketNum<=0){ flag = false; return ; } Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"买到了"+ticketNum--); } }
publicclassUnsafeList{ publicstaticvoidmain(String[] args){ List<String> list = new ArrayList<String>(); for (int i = 0; i < 10000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } System.out.println(list.size()); } }