赞
踩
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/77688880冷血之心的博客)
synchronized是Java提供的内部锁,里边有类锁和对象锁;在静态方法中,我们一般使用类锁,在实例方法中,我们一般使用对象锁,接下来,分析类锁和对象锁的区别和联系。
1、两个同步块使用同一个对象锁:
- public class Main {
- static Main objMain = new Main();
- public static void main(String[] args) {
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- Main.method2();
- }
- }).start();
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- Main obj = new Main();
- obj.method();
-
- }
- }).start();
- }
- public static void method2() {
- synchronized (objMain) {
-
- System.out.println("method2......");
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("method2....666..");
- }
- }
-
- public void method(){
- synchronized (objMain) {
- System.out.println("method...");
- }
- }
-
- }

说明:两个不同的线程在抢占同一个对象锁。
2、如果我们让两个同步块一个使用类锁一个使用对象锁:
- public class Main {
- static Main objMain = new Main();
- public static void main(String[] args) {
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- Main.method2();
- }
- }).start();
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- Main obj = new Main();
- obj.method();
-
- }
- }).start();
- }
- public static void method2() {
- synchronized (Main.class) {
-
- System.out.println("method2......");
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("method2....666..");
- }
- }
-
- public void method(){
- synchronized (objMain) {
- System.out.println("method...");
- }
- }
-
- }

此时,并不会出现锁互斥的现象,即不同的线程之间没有锁的争用。
3、如果我们将同步块中的锁均设置为类锁,即Main.class
- public class Main {
- public static void main(String[] args) {
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- Main.method2();
- }
- }).start();
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- Main obj = new Main();
- obj.method();
-
- }
- }).start();
- }
- public static void method2() {
- synchronized (Main.class) {
-
- System.out.println("method2......");
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("method2....666..");
- }
- }
-
- public void method(){
- synchronized (Main.class) {
- System.out.println("method...");
- }
- }
-
- }

此时,情况和1中一样,两个线程争用锁,一个没有释放锁,另一个线程的同步块将不会被执行。(因为此时两个线程使用了同一个类锁Main.class)
4、两个同步块中使用不同的类锁,比如一个为Main.class,另一个为Object.class。
此时,是两把不同的类锁,不会导致线程之间的锁争用,即自己执行自己的同步块即可。
5、同理,两个同步块中使用不同的对象锁,也不会导致锁争用,线程之间相互独立执行。
以上就是对synchronized中类锁和对象锁的理解,以及什么情况下会导致线程之间对锁发生争用。
如果对你有帮助,记得点赞哦~欢迎大家关注我的博客,可以进群366533258一起交流学习哦~
本群给大家提供一个学习交流的平台,内设菜鸟Java管理员一枚、精通算法的金牌讲师一枚、Android管理员一枚、蓝牙BlueTooth管理员一枚、Web前端管理一枚以及C#管理一枚。欢迎大家进来交流技术。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。