Java多线程同步之Lock用法

从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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值