import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 演示Lock的使用 */ public class UserLock { private static Lock lock = new ReentrantLock(); private static void execute(){ lock.lock(); // 获取锁 try { System.out.println(Thread.currentThread().getName() + "得到了锁"); System.out.println(Thread.currentThread().getName() + "is running."); // 模拟处理任务 }finally{ System.out.println(Thread.currentThread().getName() + "释放了锁"); lock.unlock(); // 释放锁 } } private static class UserThread extends Thread{ public UserThread(String name){ super(name); } @Override public void run() { execute(); } } public static void main(String [] args) { for (int i=0; i < 5; i++){ UserThread thread = new UserThread("第" + (i+1) + "个线程"); thread.start(); } } }