Lock接口的认识和使用

保证线程安全演进:

synchronized

volatile

AtomicInteger

 

Lock接口提供的方法:

void lock():加锁

void unlock():解锁

void lockInterruptibly():在多个线程并发获取锁的时候,那么,当有些线程拿不到锁时会等待,会不停的去抢占资源,在抢占的过程中,使用synchronized是无法进行中断的,那么,使用lockInterruptibly()方法,如果在抢占过程中发出一个中断,是可以中断的。

tryLock():非阻塞的获取锁,如果获取锁成功,返回true;否则,返回false

 

package com.roocon.thread.t9;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Sequence {

    private int value;
    Lock lock = new ReentrantLock();//所有的线程用一把锁,来保证线程安全

    public  int getNext() {
        lock.lock();
        int a = value ++;
        lock.unlock();
        return a;
    }

    public static void main(String[] args) {

        Sequence s = new Sequence();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true) {
                    System.out.println(Thread.currentThread().getName() + " " + s.getNext());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true) {
                    System.out.println(Thread.currentThread().getName() + " " + s.getNext());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true) {
                    System.out.println(Thread.currentThread().getName() + " " + s.getNext());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

}

运行结果:

Thread-0 0
Thread-2 2
Thread-1 1
Thread-0 3
Thread-1 5
Thread-2 4
Thread-0 6
Thread-1 7
Thread-2 8
...

 

Lock需要显示的获取锁和释放锁,繁琐能让代码更灵活;

使用Lock可以方便的实现公平性;public ReentrantLock(boolean fair){...}

非阻塞的获取锁;

能被中断的获取锁;

超时获取锁;(在一定时间内去获取锁)

 

synchronized不需要显示的获取锁和释放锁,简单

 

posted @ 2017-12-28 20:55  凌晨六点半  阅读(680)  评论(0编辑  收藏  举报