Synchronized同步代码块时加锁对象发生改变会引发什么线程问题

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Devil_May_Cry1995/article/details/78044639
package com.Synchronized;

public class SynchronizedTest {
	public static void main(String[] args) {
		Test2 t = new Test2();
		//Test3 t = new Test3();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				t.A();
			}

		}).start();
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				t.A();
			}

		}).start();
	}
}

class Test2 {
	private Integer i = 41;

	public void A() {
		synchronized (i) {
			System.out.println(i);
			i = 45;
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

class Test3 {
	private Student s = new Student();

	public void A() {
		synchronized (s) {
			System.out.println(s);
			s.name = "李青";
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

class Student {
	public String name = "亚索";

	@Override
	public String toString() {
		return "Student [name=" + name + "]";
	}
}

41,45同时打印


李青是延迟三秒后打印的

总结:可以看出当synchronized()中被加锁的对象如果是基本类型的包装类型或者是String类型,在一个线程获得该对象的锁之后在线程体里面如果改变了其引用对象,那么他所持有的 锁会立即被释放,此时极有可能会造成安全问题,如果是一些其它类型,当我们改变它们的属性(成员变量)时,锁并不会被释放。

                                    
展开阅读全文

synchronized同步代码块问题

12-01

[code=Java]rnpackage com.boryou;rnrnimport java.text.SimpleDateFormat;rnimport java.util.Calendar;rnrnrnpublic class Testrnrnrn /**rn * @param argsrn */rn public static void main(String[] args)rn rnrn // TODO Auto-generated method stubrnrn Clock clock1 = new Clock(false);rn Clock clock2 = new Clock(false); rnrn clock1.start();rn clock2.start(); rn tryrn rn Thread.sleep(1000*60*30);rn catch (InterruptedException e)rn rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rn rnrnrnrnclass Clock extends Threadrnrn private static Integer flg = new Integer(0);rn private int mine;rn private boolean bFlg = false;rn public Clock()rn rn flg++;rn mine = flg.intValue();rn rn public Clock(boolean bFlg)rn this.bFlg = bFlg;rn flg++;rn mine = flg.intValue(); rn rn @Overridern public void run()rn rnrn while (true)rn rn synchronized(flg) rn SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); rn Calendar calendar = Calendar.getInstance();rn System.out.println(sdf.format(calendar.getTime())+ " clock " + mine +" over!"); rn rn tryrn rn Thread.sleep(1000);rn catch (InterruptedException e)rn rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rn rn rn rn rnrn[/code]rnrn关键是synchronized这里,如果我填写的是this,有时候会出现同步问题,即输出的字符串不完整。从网上搜集到的资料来看,有人说,如果填写this,就是对一个对象本身加锁,而别的对象是访问不到这个对象的,所以锁的作用就失效了。我之前测试的,也是这样。但是也有很多人在说synchronized(this)可以达到同步的效果。看到很混乱。到底synchronized(this)会有怎么样的BUG?还是有很多人这么用的。请知道的大牛详细解答下。。。 论坛

没有更多推荐了,返回首页