在JavaSE5.0中新增了一个java.util.concurrent包来支持同步。 ReentrantLock类是可重入、互斥、实现了Lock接口的锁,
它与使用synchronized方法和块具有相同的基本行为和语义,并且扩展了其能力
ReenreantLock类的常用方法有:
ReentrantLock() : 创建一个ReentrantLock实例
lock() : 获得锁
unlock() : 释放锁
一个最简单的LOCK
public class LockThread implements Runnable{ public ReentrantLock lock =new ReentrantLock(); @Override public void run() { for (int i = 0; i < 100; i++) { lock.lock(); try{ i++; }catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } } } 如上可见 ,和synchronized相比,lock锁有这显示的操作过程,需要手动指定,何时枷锁,何时释放,都可以人为控制,所以灵活性比synchronized好很多。
重入锁
package com.thread.Synchronized;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
publicclassSynchronizedBase {
private int count=100;
/*
*同步代码块
*/
public void setRow(int num){
synchronized (this) {
count = count+num;
count = count+10;
}
} */
/*
*方法中加关键字synchronized同步
*/
/* private synchronized void setRow(intnum){
count= count+num;
count= count+10;
}*/
/*
*显示LOCK实现同步,不满足条件await()等待,signalAll();唤醒
*/
public void transfer(int from, int to, double amount) throws InterruptedException { bankLock.lock(); try { while (accounts < amount) //不满足条件,等待 sufficientFunds.await(); // System.out.print(Thread.currentThread()); accounts[from] -= amount; // System.out.printf(" .2f from %d to %d", amount, from, to); accounts[to] += amount; // System.out.printf(" Total Balance: .2f%n", getTotalBalance()); sufficientFunds.signalAll(); } finally { bankLock.unlock(); } }
}
package com.thread.Synchronized;
public class MyThread implements Runnable{
static SynchronizedBasebase ;
private int num;
MyThread(SynchronizedBase base){
this.base=base;
}
@Override
publicvoid run() {
for (inti = 0; i < 100; i++) {
base.setRow(1);
System.out.println("账户余额为"+base.getRows());
}
}
publicstaticvoid main(String[] args)throws InterruptedException {
base =new SynchronizedBase();
MyThread myThread =new MyThread(base);
Thread thread =new Thread(myThread);
System.out.println("线程一运行");
thread.start();
thread.sleep(100);
Thread thread2 =new Thread(myThread);
System.out.println("线程二运行");
thread2.start();
Thread thread3 =new Thread(myThread);
System.out.println("线程三运行");
thread3.start();
Thread thread4 =new Thread(myThread);
System.out.println("线程四运行");
thread4.start();
}
}