`
shhero
  • 浏览: 3396 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

java线程同步,线程通信

    博客分类:
  • java
 
阅读更多

1,线程同步:synchronized关键字,有一个锁对象,可以让多个线程对某个方法或某段代码互斥执行,从而可以实现多个线程安全的对共享数据并发操作等需求。(锁同时只能被一个线程拥有,线程甲执行完同步代码后释放锁,另一线程乙才能得到锁执行同步代码,各线程之间没有通信往来,由jvm自动调度,系统开销比较大,如果要实现线程间通信就用下面讲到的wait notify)参见http://baike.baidu.com/view/1207212.htm


2,线程通信:使用Object的wait和notify方法,两个方法成对使用,各线程须使用同一个锁对象。参见http://blog.csdn.net/aming2006/article/details/4463979

	Object locker=new Object();

	//假设线程A执行下面代码
	/**
	 * synchronized让当前线程A得到对象锁,一个线程只有得到锁才能调用锁的wait或notify方法,如api所讲
	 *  This method should only be called by a thread that is the owner of this object's monitor. 
	 *  A thread becomes the owner of the object's monitor in one of three ways:
	 *  
     * By executing a synchronized instance method of that object.
     * By executing the body of a synchronized statement that synchronizes on the object.
     * For objects of type Class, by executing a synchronized static method of that class. 
     * 
     * Only one thread at a time can own an object's monitor. 
     * 从api可以看到三种得到对象锁的方法都与synchronized有关,所以通常我们看到wait和notify都写在synchronized代码中
     * api说的the owner of the object's monitor与我们常说的对象锁是一个意思:
     * ‘A thread is the owner of the object's monitor’就是‘一个线程拥有了那个对象锁’之意
     * Only one thread at a time can own an object's monitor. 一个对象锁同时只能被一个线程所拥有
	 */
	//线程A得到锁对象后才能执行同步块中的代码
	synchronized(locker)	
	{
	  if(*)
	  {
			locker.wait();//线程A等待 并释放锁,待其它线程得到锁并调用notify并释放锁后 当前线程A从此处继续执行下面代码
			doSth
	  }
	}
	doSth


	//假设线程B执行下面代码
			synchronized(locker)
			{
			locker.notify();//通知线程A醒来工作
			  doSth
			}//至此线程B释放锁,如果线程A在这个锁对象上wait,则A将继续执行
 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics