synchronized
用法
1. synchronized方法和synchronized块
修饰对象
1. 代码块
2. 方法,作用对象是调用该方法的类
3. 静态方法,作用对象是该方法类的所有对象
4. 类,作用对象是该类的所有对象
实例分析
1. 实例一
package com.chen.test;
/**
* @time 2016年6月4日
* @author CHEN
*
*/
public class MyThread extends Thread{
private MyTest mt ;
public MyThread(MyTest mt ) {
this.mt =mt ;
}
@Override
public void run() {
synchronized (mt ) {
System. out.println(mt );
System. out.println("有一个线程正在进行" );
while(true ){}
}
}
public static void main(String[] args) {
//返回同一个单例
//MyThread mthread1=new MyThread(MyTest.getMyTest());
//MyThread mthread2=new MyThread(MyTest.getMyTest());
//返回新的对象
MyThread mthread1=new MyThread(MyTest.newMyTest ());
MyThread mthread2=new MyThread(MyTest.newMyTest ());
//开始方法
mthread1.start();
mthread2.start();
}
}
class MyTest {
private static final MyTest mt= new MyTest();
public MyTest(){}
//返回一个单例
public static MyTest getMyTest() {
return mt ;
}
//返回新的对象
public static MyTest newMyTest() {
return new MyTest();
}
}
假如MyTest返回一个对象的方法使用的是getMyTest()的话,获得静态的实例,那么我们就会对他进行锁定,锁定的是这一个对象。
但是如果使用的是newMyTest()的话,返回的是一个新的实例,返回的是一个新的实例,那么相当于拿到了两个加锁的实例,互不干扰。
1. 实例二
package com.chen.test;
/**
* @time 2016年6月4日
* @author CHEN
*
*/
public class MyThread extends Thread{
private MyTest mt ;
public MyThread(MyTest mt ) {
this.mt =mt ;
}
@Override
public void run() {
synchronized (MyTest.class) {//请注意此行已经和以前不一样了
System. out.println(mt );
System. out.println("有一个线程正在进行" );
while(true ){}
}
}
public static void main(String[] args) {
//返回同一个单例
//MyThread mthread1=new MyThread(MyTest.getMyTest());
//MyThread mthread2=new MyThread(MyTest.getMyTest());
//返回新的对象
MyThread mthread1=new MyThread(MyTest.newMyTest ());
MyThread mthread2=new MyThread(MyTest.newMyTest ());
//开始方法
mthread1.start();
mthread2.start();
}
}
class MyTest {
private static final MyTest mt= new MyTest();
public MyTest(){}
//返回一个单例
public static MyTest getMyTest() {
return mt ;
}
//返回新的对象
public static MyTest newMyTest() {
return new MyTest();
}
}
请注意第20行代码,把对象改成了类,凡是这个类的对象都会被拦截。
总结
synchronized(Object obj)其中obj就是要锁定的条件,如果是类,那就是类的锁定,如果是对象,那就是对象的锁定。