不安全案例()-其他
不安全案例()
package edu.wtbu;//不安全的买票public class Demo08 { public static void main(String[] args) { buyTicket buyTicket = new buyTicket(); new Thread(buyTicket,"我").start(); new Thread(buyTicket,"你").start(); new Thread(buyTicket,"黄牛党").start(); }}class buyTicket implements Runnable{ private int ticketNums=10;//票 boolean flag=true;//外部停止方式 @Override public void run() { //买票 while (flag){ try { buy(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } public void buy() throws InterruptedException { //判断是否有票 if(ticketNums<=0){ flag=false; return; } //模拟延时 Thread.sleep(1000); //买票 System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--); }}
————————
package edu.wtbu;//不安全的买票public class Demo08 { public static void main(String[] args) { buyTicket buyTicket = new buyTicket(); new Thread(buyTicket,"我").start(); new Thread(buyTicket,"你").start(); new Thread(buyTicket,"黄牛党").start(); }}class buyTicket implements Runnable{ private int ticketNums=10;//票 boolean flag=true;//外部停止方式 @Override public void run() { //买票 while (flag){ try { buy(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } public void buy() throws InterruptedException { //判断是否有票 if(ticketNums<=0){ flag=false; return; } //模拟延时 Thread.sleep(1000); //买票 System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--); }}