synchronized关键字

来源:互联网 发布:python标准输入输出 编辑:程序博客网 时间:2024/05/16 06:24

synchronized关键字

为什么需要同步关键字?因为存在并发,比较常见的例子是单例的懒汉模式,需要在获取对象的方法上加synchronized,不然可能产生new了2个对象的情况。

代码

public class TestSynchronized {    /**     * 同步方法     */    public static synchronized void staticMethod() {        int i = 3;        while (i-- > 0) {            System.out.println(Thread.currentThread().getName() + " : " + i);            try {                Thread.sleep(1000);            } catch (InterruptedException ie) {            }        }    }    public synchronized void method() {        int i = 3;        while (i-- > 0) {            System.out.println(Thread.currentThread().getName() + " : " + i);            try {                Thread.sleep(1000);            } catch (InterruptedException ie) {            }        }    }    public synchronized void method2() {        int i = 3;        while (i-- > 0) {            System.out.println(Thread.currentThread().getName() + " : " + i);            try {                Thread.sleep(1000);            } catch (InterruptedException ie) {            }        }    }    public void objMethod() {        synchronized (this) {            int i = 3;            while (i-- > 0) {                System.out.println(Thread.currentThread().getName() + " : " + i);                try {                    Thread.sleep(1000);                } catch (InterruptedException ie) {                }            }        }    }    public void classMethod() {        synchronized (TestSynchronized.class) {            int i = 3;            while (i-- > 0) {                System.out.println(Thread.currentThread().getName() + " : " + i);                try {                    Thread.sleep(1000);                } catch (InterruptedException ie) {                }            }        }    }    /**     * 1. 同步静态方法(类锁) <br/>     * 2. 同步方法(对象锁) <br/>     * 3. 同步对象代码(对象锁) <br/>     * 4. 同步类代码(类锁) <br/>     *      * 对象锁锁住当前对象,类锁锁住当前类,类锁和对象锁不冲突     */    public static void main(String[] args) {        test1();    }    // test    public static void test1() {        final TestSynchronized ts1 = new TestSynchronized();        final TestSynchronized ts2 = new TestSynchronized();        Thread thread1 = new Thread(new Runnable() {            public void run() {                ts1.objMethod();            }        }, "thread1");        Thread thread2 = new Thread(new Runnable() {            public void run() {                ts2.classMethod();            }        }, "thread2");        thread1.start();        thread2.start();    }}

总结

1.同步的静态的方法(类锁)
2.同步的方法(对象锁)
3.同步的对象的代码(对象锁)
4.同步的类的代码(类锁)

对象锁锁住当前对象
类锁锁住当前类
类锁和对象锁不冲突

0 0
原创粉丝点击