从JDK5.0开始,有两种机制来保护代码块不受到并行访问的干扰。旧版本的Java使用synchronized关键字来达到这个目的,而JDK5.0引进了ReentrantLock()类。synchronize关键字自动提供一个锁和相关的条件。
用ReentrantLock保护代码块的结构如下:
Lock myLock = new ReentrantLock();
myLock.lock()
try{
需要保护的代码块;
}
finally{
myLock.unlock
}
下面是用法示例:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class WorkThread extends Thread{
private CourruptedData data = null ;
private int type = 0 ;
public WorkThread(CourruptedData _data,int _type){
data = _data ;
type = _type ;//快进程和满进程的标记。
super.start();
}
public void run(){
data.performWork(type);
}
}
public class CourruptedData {
protected static int display = 1 ;
protected static int change = 2 ;
private WorkThread slowWorker = null ;
private WorkThread fastWorker = null ;
private int number = 0 ;
private volatile double f = 1.1;
Lock lock = new ReentrantLock();
public CourruptedData() {
number = 1 ;
slowWorker = new WorkThread(this,display);//-----------慢进程先启动;
fastWorker = new WorkThread(this,change);
}
/*
* 关键字为synchronized时,方法修饰为同步方法,
* 慢线程调用performWokr()时,休眠两秒;
* 此时,不允许第二个线程打断第一个线程;
* 等第一个线程执行完毕之后,第二个线程才能将number改为-1;
*/
public void performWork(int type){
if (type == display)
{
lock.lock();
try{
System.out.println("Number before sleeping:" + number);
try{
slowWorker.sleep(2000);
}catch (InterruptedException ie){
System.out.println("Error : "+ie);
}
System.out.println("Number after working up:"+ number);
}
finally{
lock.unlock();
}
}
if (type == change)
{
lock.lock();
try{
System.out.println("Change the numbering:");
number = -1 ;
System.out.println(number);
}
finally{
lock.unlock();
}
}
}
public static void main(String args[])
{
CourruptedData test = new CourruptedData();
}
}