线程练习-网络买票
package cn.BuyTickets; //线程类 public class BuyTickets implements Runnable{ private int num; private int count=10; @Override public void run() { while(true) { boolean flag = buy(); if(flag == false) { return; } } } //synchronized不能放在run方法中,否则只有一人抢票 synchronized public boolean buy() { if(count==0) { System.out.println("已无票"); return false; } num++; count--; try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"抢到了第"+num+"张票,余票"+count+"张"); if("黄牛党".equals(Thread.currentThread().getName())){ return false; } return true; } }
package cn.BuyTickets; public class Main { public static void main(String[] args) { BuyTickets bt = new BuyTickets(); Thread d1 = new Thread(bt,"淘泡泡"); Thread d2 = new Thread(bt,"张票票"); Thread d3 = new Thread(bt,"黄牛党"); d1.start(); d2.start(); d3.start(); } }