转载自:http://blog.csdn.net/a19881029/article/details/8215775
Java提供了一种内置的锁机制来支持原子性
每一个Java对象都可以用作一个实现同步的锁,称为内置锁,线程进入同步代码块之前自动获取到锁,代码块执行完成正常退出或代码块中抛出异常退出时会释放掉锁
内置锁为互斥锁,即线程A获取到锁后,线程B阻塞直到线程A释放锁,线程B才能获取到同一个锁
内置锁使用synchronized关键字实现,synchronized关键字有两种用法:
1,修饰需要进行同步的方法(所有访问状态变量的方法都必须进行同步),此时充当锁的对象为调用同步方法的对象
2,同步代码块
和直接使用synchronized修饰需要同步的方法是一样的,但是锁的粒度可以更细,并且充当锁的对象不一定是this,也可以是其它对象,所以使用起来更加灵活
用synchronized关键字修饰的方法可以认为是一个横跨整个方法体的同步代码块
运行结果为:
修改上面的代码,每个线程运行时创建一个新的Status对象,而不是像上面的代码,4个线程共用同一个Status对象:
由于充当锁的对象实例不一定是同一个对象(hashcode不同),同步失效:
因此同步代码块中充当锁的对象必须为同一个对象
运行结果为:
从运行结果可以看出,在Thread线程锁定status对象的时候,Main线程在Thread线程释放锁对象前依然能够修改status对象的num域,说明锁没有生效
Main线程中没有对status对象进行同步,故在Thread线程锁定status对象的时候不需要阻塞,可以直接操作status对象,因此所有使用同步对象的地方都必须进行同步
修改方式为:Task类的main方法中,在操作status对象时进行同步(去掉代码中的注释部分)
如果锁对象为静态变量,或使用synchronized关键字修饰静态方法,则锁对象为Class对象
运行结果如下:
相当于:
或是: