多线程之不安全买票
作者:互联网
package com.lyon.demo; //不安全的买票 public class UnsafeBuyTicket { public static void main(String[] args) { BuyTicket buyTicket = new BuyTicket(); new Thread(buyTicket,"小明").start(); new Thread(buyTicket,"黄牛1").start(); new Thread(buyTicket,"黄牛2").start(); } } class BuyTicket implements Runnable{ //票 private int ticket = 10; private boolean flag = true;//线程停止标志 @Override public void run() { try{ //买票 while (flag){ buy(); } } catch (InterruptedException e) { e.printStackTrace(); } } private void buy() throws InterruptedException { //判断是否有票 if(ticket<=0){ flag = false; return; } //模拟延迟 Thread.sleep(500); //买票 System.out.println(Thread.currentThread().getName()+"拿到"+ticket--); } }
标签:Thread,start,private,安全,buyTicket,new,买票,多线程,public 来源: https://blog.csdn.net/u014381566/article/details/115271585