在java多线程中,可以使用synchronized关键字实现线程之间的同步互斥,在jdk1.5中增加的ReentrantLock也能实现同样的效果,并且功能更加强大。
比如具有嗅探锁定,多路分支通知等功能,在使用上比synchronized更加灵活。
1.Object类中的wait()方法相当于Condition类中的await()方法
2.Object类中的wait(long timeout)相当于Condition类中的await(long time,TimeUnit unit)方法
3.Object类中的notify()方法相当于Condition类中的signal()方法
4.Object类中的notifyAll()方法相当于Condition类中的signalAll()方法
public class MyService { private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public void await() { try { lock.lock(); System.out.println("await:" + System.currentTimeMillis()); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void signal(){ try{ lock.lock(); System.out.println("signal:"+System.currentTimeMillis()); condition.signal(); }finally { lock.unlock(); } } } public class ThreadA extends Thread{ private MyService myService; public ThreadA(MyService myService) { this.myService = myService; } @Override public void run() { myService.await(); } } public class Run { public static void main(String[] args) throws InterruptedException { MyService myService=new MyService(); ThreadA a = new ThreadA(myService); a.start(); Thread.sleep(1000); myService.signal(); } }
输出:
await :1531289025398
signal:1531289026398