JAVA后台开发_从入门到精通

7 Java并发Lock接口

2017-08-31  本文已影响15人  笑Skr人啊

java.util.concurrent.locks.Lock接口用作线程同步机制,类似于同步块。新的锁定机制更灵活,提供比同步块更多的选项。 锁和同步块之间的主要区别如下:

Lock类中的方法

以下是Lock类中可用的重要方法的列表。

编号 方法 描述说明
1 public void lock() 获得锁
2 public void lockInterruptibly() 获取锁定,除非当前线程中断
3 public Condition newCondition() 返回绑定到此Lock实例的新Condition实例
4 public boolean tryLock() 只有在调用时才可以获得锁
5 public boolean tryLock(long time, TimeUnit unit) 如果在给定的等待时间内自由,并且当前线程未被中断,则获取该锁。
6 public void unlock() 释放锁

示例

以下LockTest程序演示了使用Lock接口的一些方法。 这里我们使用lock()获取锁和unlock()来释放锁。

package ThreadMethod;

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

class PrintDemo1 {
    private final Lock queueLock = new ReentrantLock();

    public void print() {
        queueLock.lock();
        try {
            Long duration = (long) (Math.random() * 10000);
            System.out.println(Thread.currentThread().getName()
                    + "  Time Taken " + (duration / 1000) + " seconds.");
            Thread.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.printf("%s printed the document successfully.\n", Thread
                    .currentThread().getName());
            queueLock.unlock();
        }
    }
}

class ThreadDemo1 extends Thread {
    PrintDemo1 PrintDemo1;

    ThreadDemo1(String name, PrintDemo1 PrintDemo1) {
        super(name);
        this.PrintDemo1 = PrintDemo1;
    }

    @Override
    public void run() {
        System.out.printf("%s starts printing a document\n", Thread
                .currentThread().getName());
        PrintDemo1.print();
    }
}

public class LockTest {
    public static void main(String args[]) {
        PrintDemo1 PD = new PrintDemo1();

        ThreadDemo1 t1 = new ThreadDemo1("Thread - 1 ", PD);
        ThreadDemo1 t2 = new ThreadDemo1("Thread - 2 ", PD);
        ThreadDemo1 t3 = new ThreadDemo1("Thread - 3 ", PD);
        ThreadDemo1 t4 = new ThreadDemo1("Thread - 4 ", PD);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

运行

Thread - 2  starts printing a document
Thread - 4  starts printing a document
Thread - 3  starts printing a document
Thread - 1  starts printing a document
Thread - 2   Time Taken 2 seconds.
Thread - 2  printed the document successfully.
Thread - 4   Time Taken 7 seconds.
Thread - 4  printed the document successfully.
Thread - 3   Time Taken 9 seconds.
Thread - 3  printed the document successfully.
Thread - 1   Time Taken 9 seconds.
Thread - 1  printed the document successfully.


在上面的示例中,使用ReentrantLock类作为Lock接口的一个实现。 ReentrantLock类允许线程锁定方法,即使它已经具有其他方法锁。

上一篇 下一篇

猜你喜欢

热点阅读