同步方法就是把synchronized加到方法上。

格式:修饰符 synchronized 返回值类型 方法名(形式参数){ }

同步代码块和同步方法的区别:

  1、同步代码块可以锁住指定代码。同步方法是锁住方法中所有代码;

  2、同步代码块可以指定锁对象,同步方法不能指定锁对象,同步方法的锁对象是this

静态同步方法格式:修饰符 static synchronized 返回值类型 方法名(形式参数){ },静态同步方法因为没有this,所以它的锁对象是类名.class,实际上就是这个类的class文件的对象

public class MyRunnable implements Runnable {

    private static int ticket = 100;

    @Override
    public void run() {
        while (true) {
            boolean result = method();
            if (result)
                System.out.println("票卖完了");
        }
    }

    public synchronized boolean method() {

        if (ticket == 0)
            return true;

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ticket--;
        System.out.println(Thread.currentThread().getName() + "卖票了,还剩" + ticket + "张票");
        return false;
    }
}