synchronized详解

这几天一直在研究多线程的东西,对于synchronized又有了另一份理解。

看代码:

public class AtomicIntegerTest2 {
	static Object o = new Object();//同步锁对象
	
	public static int count = 0;
 
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
           new MyThread().start();
        }
    }
}

class MyThread extends Thread{
	String str ="000";//同步锁对象,可以同步
	String str2 =new String();//同步锁对象,不可同步
	Integer it = 0;//同步锁对象,可以同步
	Integer it2 = new Integer(0);//同步锁对象,不可同步
	@Override
	public void run() {
		//this:无法同步,因为this指的就是MyThread的实例,主线程每次都是new新的所以无法同步
		//str字符串类型,一旦声明地址无法改变  但是只能是String Str = "123"这样声明。这个是可以同步的
		//String str =new String(); 这种声明无法同步,因为每次都会有个新的string对象产生
		//所以得出同步对象必须满足在线程体当中对象地址不能改变,只要满足这个条件就可以当做同步对象,例如:静态对象,字符串常量等。
		synchronized (it) {
			for (int j = 0; j < 10; j++) {
				str+= "123";//虽然字符串的内容变化了,但是str="000"地址始终存在,所以可以同步
				it ++;//整型对象改变
				AtomicIntegerTest2.count++;
				System.out.println(Thread.currentThread().getName()+"值:"+AtomicIntegerTest2.count);
	        }
		}
	}
}

运算结果也是同步的

 
 


版权声明:本文为jhhuang4836原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。