1. 编程模型
public void some_method()
{
reentrantlock.lock();
try
{
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
reentrantlock.unlock();
}
}
2. 示例
package com.hp.learn.concurrency.lock;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class Worker implements Runnable {
private String name;
private ReentrantLock reentrantLock;
public Worker(String name, ReentrantLock reentrantLock) {
this.name = name;
this.reentrantLock = reentrantLock;
}
@Override
public void run() {
boolean done = false;
while (!done) {
boolean ans = reentrantLock.tryLock();
if (ans) {
try {
Date d = new Date();
SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
System.out.println("task name -" + name
+ "outer lock acquired at "
+ ft.format(d)
+ "Doing outer work");
Thread.sleep(1500);
reentrantLock.lock();
try {
d = new Date();
ft = new SimpleDateFormat("hh:mm:ss");
System.out.println("task name -" + name
+ "inner lock acquired at "
+ ft.format(d)
+ "Doing outer work");
System.out.println("Lock Hold Count - " + reentrantLock.getHoldCount());
Thread.sleep(1500);
} catch (InterruptedException e) {
log.error("Interrupt", e);
} finally {
System.out.println("task name - " + name +
"releasing inner lock");
reentrantLock.unlock();
}
System.out.println("Lock Hold Count - " + reentrantLock.getHoldCount());
System.out.println("task name - " + name + "work done");
done = true;
} catch (InterruptedException e) {
log.error("Interrupt", e);
} finally {
System.out.println("task name -" + name +
"releasing outer lock");
reentrantLock.unlock();
System.out.println("Lock Hold Count -" +
reentrantLock.getHoldCount());
}
} else {
System.out.println("task name - " + name +
"waiting for lock");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error("Interrupt", e);
}
}
}
}
}
package com.hp.learn.concurrency.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
static final int MAX_T = 2;
public static void main(String[] args) {
ReentrantLock reentrantLock = new ReentrantLock();
ExecutorService pool = Executors.newFixedThreadPool(MAX_T);
Runnable w1 = new Worker("Job1", reentrantLock);
Runnable w2 = new Worker("Job2", reentrantLock);
Runnable w3 = new Worker("Job3", reentrantLock);
Runnable w4 = new Worker("Job4", reentrantLock);
pool.execute(w1);
pool.execute(w2);
pool.execute(w3);
pool.execute(w4);
pool.shutdown();
}
}