Java并发编程实践读书笔记(一)

来源:互联网 发布:吴昕淘宝店铺网址 编辑:程序博客网 时间:2024/06/05 02:56

Lock

java.util.concurrent.lock 的ReentrantLock基本用法:
Lock lock = new ReentrantLock(); lock.lock(); //critical section lock.unlock();
其功能被称为synchronized的替代,具有相同的语义、相同的功能。
原文:

The Lock interface has the following primary methods:

  • lock()
  • lockInterruptibly()
  • tryLock()
  • tryLock(long timeout, TimeUnit timeUnit)
  • unlock()

The lock() method locks the Lock instance if possible. If the Lock instance is already locked, the thread calling lock() is blocked until the Lock is unlocked.

The lockInterruptibly() method locks the Lock unless the thread calling the method has been interrupted. Additionally, if a thread is blocked waiting to lock the Lock via this method, and it is interrupted, it exits this method calls.

The tryLock() method attempts to lock the Lock instance immediately. It returns true if the locking succeeds, false if Lock is already locked. This method never blocks.

The tryLock(long timeout, TimeUnit timeUnit) works like the tryLock() method, except it waits up the given timeout before giving up trying to lock the Lock.

The unlock() method unlocks the Lock instance. Typically, a Lock implementation will only allow the thread that has locked the Lock to call this method. Other threads calling this method may result in an unchecked exception (RuntimeException).

Condition

经常与Lock一起用到的Condition:
Lock lock = new ReentrantLock();Conditon con = lock.newCondition();// your codecon.await();
对于Condition常用的方法有awaite(),signal(),signalAll();分别对应Object对象中waite(),notify(),notifyall()。功能用法完全一样
在这里需要提一下waite() 和 sleep(),以前我只知道一个是挂起,一个是休眠。 其实两者都可以让线程暂停一段时间,但是本质的区别是一个线程的运行状态控制sleep(),一个是线程之间的通讯的问题  wait()。 sleep()可以将一个线程睡眠,参数可以指定一个时间。 而wait()可以将一个线程挂起,直到超时或者该线程被唤醒。
sleep和wait的区别有:
  1,这两个方法来自不同的类分别是Thread和Object
  2,最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法。
  3,wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在
    任何地方使用
   synchronized(x){
      x.notify()
     //或者wait()
   }
   4,sleep必须捕获异常,而wait,notify和notifyAll不需要捕获异常

ReadWriteLock

writeLock: 
    一次一个writer可以访问共享数据
readLock:
    多个线程可以同时读取共享数据
原创粉丝点击