synchronized

对象锁

public class HelloWorld {
    public String sayHello() {
        return "Hello World";
    }

    public int getAge() {
        return 10;
    }

    public synchronized void test() {
        System.out.println("test()");

    }

    public synchronized void forever() {
        int index = 0;
        while (true) {
            System.out.println("index:" + index + ", thread id:"
                    + Thread.currentThread().getId());
            try {
                System.out.println("sleep");
                Thread.sleep(2000);
            } catch (Exception e) {
                System.out.println("Exception:");
                e.printStackTrace();
            }
        }
    }

    public static void main(String s[]) {
        final HelloWorld hw = new HelloWorld();

        Thread thread = new Thread() {
            @Override
            public void run() {
                hw.forever();
            }
        };

        thread.start();

        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            System.out.println("Exception:");
            e.printStackTrace();
        }

        hw.test();
    }
}

test()无法print

 

类锁

package com.unit.example;

public class HelloWorld {
    public String sayHello() {
        return "Hello World";
    }

    public int getAge() {
        return 10;
    }

    public static synchronized void test() {
        System.out.println("test()");

    }

    public static synchronized void forever() {
        int index = 0;
        while (true) {
            System.out.println("index:" + index + ", thread id:"
                    + Thread.currentThread().getId());
            try {
                System.out.println("sleep");
                Thread.sleep(2000);
            } catch (Exception e) {
                System.out.println("Exception:");
                e.printStackTrace();
            }
        }
    }

    public static void main(String s[]) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                HelloWorld.forever();
            }
        };

        thread.start();

        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            System.out.println("Exception:");
            e.printStackTrace();
        }

        HelloWorld.test();
    }
}

test()无法print

由此验证synchronized锁住的是对象或类,而不是代码块。

posted @ 2015-03-18 20:47  牧 天  阅读(152)  评论(0)    收藏  举报