先说下Lock 这个东西
ReentrantLock获取锁定与三种方式:(来自百度知道)
a) lock(), 如果获取了锁立即返回,如果别的线程持有锁,当前线程则一直处于休眠状态,直到获取锁
b) tryLock(), 如果获取了锁立即返回true,如果别的线程正持有锁,立即返回false;
c)tryLock(long timeout,TimeUnit unit), 如果获取了锁定立即返回true,如果别的线程正持有锁,会等待参数给定的时间,在等待的过程中,如果获取了锁定,就返回true,如果等待超时,返回false;
d) lockInterruptibly:如果获取了锁定立即返回,如果没有获取锁定,当前线程处于休眠状态,直到或者锁定,或者当前线程被别的线程中断
贴下源码
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class RunnableDemo {
static Lock lock=new ReentrantLock();
static int cnt=28;
static int who=0;
public static void main(String[] args) {
Thread a=new Thread(){
public void run() {
// TODO Auto-generated method stub
super.run();
while(who
lock.lock();
if(who%3==0){
System.out.println("AAAAA "+who);
who++;
}
lock.unlock();
}
}
};
Thread b=new Thread(){
public void run() {
// TODO Auto-generated method stub
super.run();
while(who
lock.lock();
if(who%3==1){
System.out.println("BBBBB "+who);
who++;
}
lock.unlock();
}
}
};
Thread c=new Thread(){
public void run() {
// TODO Auto-generated method stub
super.run();
while(who
lock.lock();
if(who%3==2){
System.out.println("CCCCC "+who);
who++;
}
lock.unlock();
}
}
};
a.start();
b.start();
c.start();
}
}程序输出结果:
AAAAA 0
BBBBB 1
CCCCC 2
AAAAA 3
BBBBB 4
CCCCC 5
AAAAA 6
BBBBB 7
CCCCC 8
AAAAA 9
BBBBB 10
CCCCC 11
AAAAA 12
BBBBB 13
CCCCC 14
AAAAA 15
BBBBB 16
CCCCC 17
AAAAA 18
BBBBB 19
CCCCC 20
AAAAA 21
BBBBB 22
CCCCC 23
AAAAA 24
BBBBB 25
CCCCC 26
AAAAA 27
BBBBB 28
CCCCC 29