java synchronized

package com.test;

import lombok.SneakyThrows;
import lombok.Synchronized;

public class Ticket implements  Runnable {
    private volatile int ticketNums=100;
    @SneakyThrows
    @Override
    public void run() {
        while(true) {
            sale();
//            synchronized (Ticket.class) {//第一种代码块
//                if (ticketNums > 0) {
//                    Thread.sleep(10);
//                    System.out.println(Thread.currentThread().getName() + " sale " + ticketNums + " ticket");
//                    ticketNums--;
//                }
//            }
        }
    }
    public synchronized void sale() throws InterruptedException {//第二种方法块
if (ticketNums > 0) { Thread.sleep(10); System.out.println(Thread.currentThread().getName() + " sale " + ticketNums + " ticket"); ticketNums--; } } }

  

原文地址:https://www.cnblogs.com/howhy/p/15205257.html