美文网首页
多线程共享数据的简单例子

多线程共享数据的简单例子

作者: hs_jianshu | 来源:发表于2018-02-26 01:18 被阅读0次

    package com.hs.thread.ticket;

    /**

    • Created by husong on 2018/2/26.
      */
      public class TicketHandler {

      private Integer ticketNum = 100;

      public synchronized int sell(){
      if(ticketNum>0){
      try {
      Thread.sleep(1000);
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      ticketNum --;
      System.out.println(Thread.currentThread().getName()+"抢到一张票!"+"余票数量:"+ticketNum);
      }
      return ticketNum;
      }

      public synchronized int tuiPiao(){
      try {
      Thread.sleep(1000);
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      ticketNum++;
      System.out.println(Thread.currentThread().getName()+"退了一张票!"+"余票数量:"+ticketNum);
      return ticketNum;
      }

      public static void main(String[] args) {
      TicketHandler ticketHandler = new TicketHandler();
      //5个人买票
      for (int i = 1; i <= 5; i++) {
      Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
      Integer num = ticketHandler.sell();
      }
      });
      thread.setName("旅客"+i);
      thread.start();
      }
      //5个人退票
      for (int i = 6; i <= 10; i++) {
      Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
      Integer num = ticketHandler.tuiPiao();
      }
      });
      thread.setName("旅客"+i);
      thread.start();
      }
      }
      }

    相关文章

      网友评论

          本文标题:多线程共享数据的简单例子

          本文链接:https://www.haomeiwen.com/subject/acwdxftx.html