java多线程模拟抢票

时间:2022-12-29 16:47:44

public class Test {
 public static void main(String[] args) throws InterruptedException {
  int time = 50;
  int num = 50;
  int people = 100;
  TestThread t1 = new TestThread();
  Thread[] thread = new Thread[people];
  for (int i = 1; i < people; i++) {
   thread[i] = new Thread(t1);
   thread[i].start();
  }
  Thread.sleep(num * time);
  System.out.println("tickets are over");

 }

}

class TestThread implements Runnable {
 int ticket = 50;
 String str = " ";
 int time = 50;

 public void run() {
  if (ticket > 0) {
   synchronized (str) {
    if (ticket > 0) {
     System.out.println(Thread.currentThread().getName()
       + ": taker  get " + ticket + " ticket");
     ticket--;
    }
   }
  }
  try {
   Thread.sleep(time);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}