下面演示Locks 的使用。代码如下:package com.Android.test;import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* 重入锁的使用方式如下: Lock l = ...; l.lock(); try { // access the resource protected by this lock } finally { l.unlock(); } */public class ReentrantLockDemo implements Runnable { private int number = 0; // 定义一个重入锁 private Lock lock = new ReentrantLock(); @Override public void run() { // TODO Auto-generated method stub lock.lock(); try { for (int i = 0; i < 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + number++); } } finally{ lock.unlock(); } }
public static void main(String [] args){ ReentrantLockDemo run = new ReentrantLockDemo(); Thread thread1 = new Thread(run); Thread thread2 = new Thread(run);