MyException - 我的异常网
当前位置:我的异常网» 编程 » Synchronized块同步方法中this跟class对象

Synchronized块同步方法中this跟class对象

www.MyException.Cn  网友分享于:2013-02-20  浏览:0次
Synchronized块同步方法中this和class对象

synchronized关键字有两种用法。第一种就是使用Synchronized关键字同步类方法。另外一种就是synchronized块

public  void add(String name){
		synchronized (this) {
		   name = "this->"+name;
		   System.out.println(Thread.currentThread()+"name:"+name);
		}
	}
	
	public synchronized  void delete(String name){
		name = "delete-->"+name;
		System.out.println(Thread.currentThread()+name);
	}

 syncronized块中this和class对象的主要应用区别

 

1.非静态方法可以使用this或者class对象来同步,而静态方法必须使用class对象来同步并且它们互不影响

2.this是针对当前引用的对象,class对象就是原始对象本身

public class Test{
	

	public static void main(String[] args){
		MyThread m = new MyThread("liming");
		MyThread m1 = new MyThread("yaotian");
		Thread t = new Thread(m);
		Thread t1 = new Thread(m1);
	    t.start();
	    t1.start();
	}
}
 
class MyThread implements Runnable{
   
    private String name;
    
    public MyThread(String name){
    	this.name=name;
    }
    
	public void run() {
		add(name);		
	}

	public  void add(String name){
		synchronized (MyThread.class) {
		   name = "this->"+name;
		   System.out.println(Thread.currentThread()+"name:"+name);
		   delete(name);
		}
	}
	
	public synchronized  void delete(String name){
		name = "delete-->"+name;
		System.out.println(Thread.currentThread()+name);
	}
}

 在synchronized同步块中使用了MyThread.class对象作为监视器,并且生成了m,m1对MyThread引用对象,创建了两个线程t,t1来分别访问m,m1,最后得到的结果是:(这个结果是符合预期的结果,线程执行的顺序是先执行add后执行delete)

Thread[Thread-0,5,main]name:this->liming
Thread[Thread-0,5,main]delete-->this->liming
Thread[Thread-1,5,main]name:this->yaotian
Thread[Thread-1,5,main]delete-->this->yaotian

-----------------------------
Thread[Thread-1,5,main]name:this->yaotian
Thread[Thread-1,5,main]delete-->this->yaotian

Thread[Thread-0,5,main]name:this->liming
Thread[Thread-0,5,main]delete-->this->liming

如果我们将add中的同步监视器改为this结果是方法不同步

Thread[Thread-0,5,main]name:this->liming
Thread[Thread-1,5,main]name:this->yaotian
Thread[Thread-0,5,main]delete-->this->liming
Thread[Thread-1,5,main]delete-->this->yaotian

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有