疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

java同步机制


 

        内建同步块,同步方法:

  public static class Syn {

  synchronized void funA() throws InterruptedException {

  wait();

  System.out.println("synchronized functionA()");

  }

  void funB() {

  synchronized (MyThread.Syn.this) {

  System.out.println("synchronized functionB()");

  notifyAll();

  }

  }

  Runnable instanceA() {

  return new Runnable() {

  @Override

  public void run() {

  // TODO Auto-generated method stub

  try {

  funA();

  } catch (InterruptedException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  }

  };

  }

  Runnable instanceB() {

  return new Runnable() {

  @Override

  public void run() {

  // TODO Auto-generated method stub

  funB();

  }

  };

  }

  public static void main(String[] args) {

  Syn syn = new Syn();

  new Thread(syn.instanceA()).start();

  new Thread(syn.instanceB()).start();

  }

  }

  wait(),notify()只能在同步块或方法中执行,否则抛出InterruptedException

  同步锁lock提供lock,unlock,trylock,lock.lockInterruptibly();注意应该在finally块中释放锁

  内置condition类,可以实现更复杂的控制(参见实例),它提供了类似wait/notify的功能,signal/await,必须在condition的lock块中使用。

  read,lock锁,可以实现一个读取并行,写入串行的锁

  static public class LockTest {

  Lock lock = new ReentrantLock();

  Condition conditionEmpty = lock.newCondition();

  Condition conditionFull = lock.newCondition();

  ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

  Lock readLock = readWriteLock.readLock();

  Lock writeLock = readWriteLock.writeLock();

  ArrayList arrayList = new ArrayList<>();

  int max = 1000;

  String getCommonLock(int i) {

  lock.lock();

  try {

  return arrayList.get(i);

  } finally {

  lock.unlock();

  }

  }

  void setCommonLock(String string) {

  lock.lock();

  try {

  arrayList.add(string);

  } finally {

  lock.unlock();

  }

  }

  String remove(int i) throws InterruptedException {

  lock.lock();

  try {

  while (arrayList.size() == 0) {

  conditionEmpty.await();

  }

  conditionFull.signalAll();

  return arrayList.remove(i);

  } finally {

  lock.unlock();

  }

  }

  void insert(String string) throws InterruptedException {

  lock.lock();

  try {

  while (arrayList.size() == 0) {

  conditionFull.await();

  }

  conditionEmpty.signalAll();

  arrayList.add(string);

  } finally {

  lock.unlock();

  }

  }

  String getReadLock(int i) {

  readLock.lock();

  try {

  return arrayList.get(i);

  } finally {

  readLock.unlock();

  }

  }

  void setWriteLock(String string) {

  writeLock.lock();

  try {

  arrayList.add(string);

  } finally {

  writeLock.unlock();

  }

  }

  }

  同步类:blockQueue,contrunt****简单略去,注意的是他们使用lock机制实现了锁定,因此当使用java内部锁锁定同步类本身时不能实现对象分布

  CountDownLatch/CyclicBarrier,用以控制各个线程到达同一位置后继续执行,提供线程间协调方法

  Semaphore,用来发布可以被n各线程访问的资源(lock发布了一个可以被一个线程访问的资源)