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

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();
    }
    }
    }

你可能感兴趣的:(多线程共享数据的简单例子)