今天做了一个小实验,关于Reentrantlock ,不知道自己理解的对不对。
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
public void outer(){
System.out.println("this is outer "+Thread.currentThread().getName());
inter();
}
public void inter(){
System.out.println("this is inter"+Thread.currentThread().getName());
}
public static void main(String[] args) {
LockTest test = new LockTest();
ReentrantLock lock = new ReentrantLock();
Condition con = lock.newCondition();
Thread test1 = new Thread(new RunTest1(test,lock,con),"task1");
Thread test2 = new Thread(new RunTest2(test,lock,con),"task2");
test1.start();
test2.start();
}
}
class RunTest1 implements Runnable{
private LockTest lTest;
ReentrantLock lock ;
Condition con;
public RunTest1(LockTest lTest,ReentrantLock lock,Condition con ){
this.lock = lock;
this.lTest = lTest;
this.con = con;
}
@Override
public void run() {
//task1 上锁
lock.lock();
try {
System.out.println("this is :"+Thread.currentThread().getName());
//然后直接让task1 进入等待,这时候并没有释放锁
con.await(5,TimeUnit.SECONDS);
lTest.inter();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
class RunTest2 implements Runnable{
private LockTest lTest;
ReentrantLock lock ;
Condition con;
public RunTest2(LockTest lTest,ReentrantLock lock,Condition con){
this.lTest = lTest;
this.lock = lock;
this.con = con;
}
@Override
public void run() {
//得到锁
lock.lock();
System.out.println("this is :"+Thread.currentThread().getName());
//执行方法 task2
lTest.outer();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//释放 这里如果不释放锁,则上面task1 await结束后也会等待锁释放而无法执行下面的方法
lock.unlock();
}
}
}
ReentrantLock 当Condition.await() 释放资源的时候,锁也会放掉,然后其他线程就可以获得锁然后执行任务,当await时间到了的时候就会再次去竞争锁。
this is :task1
this is :task2
this is outer task2
this is intertask2
this is intertask1
囧。。一天时间竟搞点没用的东西。。。
PS.哎 找不到工作呀。求大牛带学呀。。一个人自学太苦逼了。。。。