Java simulation multithreading implementation of ticket grabbing code example

This article mainly introduces the implementation of java simulation multithreading to grab tickets. It is introduced in great detail through the example code, which has a certain reference value for everyone's study or work. Friends in need can refer to it

Demo of rush purchase of 100 tickets

Here you need a variable to save 100 sheets

Local variables:

Member variables:

Static member variables:

problem

1. Abnormal sales sequence

2. A ticket has been sold many times

Use lock

The code is as follows

class SaleThread implements Runnable {

 /**
  * 使用静态成员变量作为100张票的保存变量,是一个共享资源。
  */
 private static int tickets = 100;

 @Override
 public void run() {

  // 完成售票过程
  while (true) {
   /*
   字符串可以作为锁对象,因为双引号包含的字符串不管在代码中如何运行,有且只有一个
    */
   synchronized ("锁") {

    try {
     Thread.sleep(500);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }

    if (tickets > 0) {
     System.out.println(Thread.currentThread().getName() + "售出了" + tickets + "张票");
     tickets--;
    } else {
     System.out.println(Thread.currentThread().getName() + "售罄!!!");
     break;
    }
   }
  }
 }
}

public class Demo {
 public static void main(String[] args) {
  Thread t1 = new Thread(new SaleThread(),"售票人员1");
  Thread t2 = new Thread(new SaleThread(),"售票人员2");
  Thread t3 = new Thread(new SaleThread(),"售票人员3");

  t1.start();
  t2.start();
  t3.start();
 }
}

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>