synchronized塊

同步塊裏面對象鎖的細節ide

synchronized塊相對於方法聲明加synchronized關鍵字,更加靈活this

例子

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
相關文章
相關標籤/搜索