日期:2014-05-20 浏览次数:20862 次
import java.util.concurrent.locks.*;
public class ReentrantLock implements Runnable{
private int num = 0;
private Lock lock = new ReentrantLock();//创建重入锁对象。这里怎么报错啊???
@Override
public void run(){
lock.lock(); //打开锁
try{
for(int i = 0; i < 5; i++){
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + num++);
}
}finally{
lock.unlock();//释放锁
}
}
public static void main(String[] args) {
ReentrantLock run = new ReentrantLock();
Thread thread1 = new Thread(run);
Thread thread2 = new Thread(run);
thread1.start();
thread2.start();
}
}