Contents
  1. 1. 例子
  2. 2. 运行结果

同步块里面对象锁的细节

synchronized块相对于方法声明加synchronized关键字,更加灵活

例子

public class FetchRunnable implements Runnable{

    private String TAG_1 = new String("TAG_1");//锁this
    private static String TAG_2 = new String("TAG_2");//锁class
    private String TAG_3 = "TAG_3";//锁class

    public void run() {
        //runClass();
        //runThis();
        runTag(TAG_1);
        sleep();
        runTag(TAG_2);
        sleep();
        runTag(TAG_3);
    }

    private void runClass() {
        synchronized (FetchRunnable.class) {
            System.out.println("run Class");
            sleep();
        }
    }

    private void runThis() {
        synchronized (this) {
            System.out.println("run this");
            sleep();
        }
    }

    private void runTag(String tag) {
        synchronized (tag) {
            System.out.println(Thread.currentThread().getName() + " run " + tag +" 秒="+Calendar.getInstance().get(Calendar.SECOND));
            sleep();
        }
    }

    private void sleep() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Thread t0 = new Thread(new FetchRunnable());
        Thread t1 = new Thread(new FetchRunnable());
        t0.start();
        t1.start();
    }
}

运行结果

Thread-0 run TAG_1 秒=18
Thread-1 run TAG_1 秒=18
Thread-1 run TAG_2 秒=20
Thread-0 run TAG_2 秒=21
Thread-1 run TAG_3 秒=22
Thread-0 run TAG_3 秒=23
Contents
  1. 1. 例子
  2. 2. 运行结果