/*
ReentrantLock.Lock实现线程互斥
*/
package threadTest;
import java.util.concurrent.locks.ReentrantLock;
/**
*ReentrantLock 的效率比
*/
public class LockThread {
ReentrantLock lock1 = new ReentrantLock();
// ReentrantLock lock2 = new ReentrantLock();
class LockInitFirst implements Runnable{
public void run() {
lock1.lock();
try {
System.out.println("lock1");
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}finally{
lock1.unlock();
}
}
}
class LockInitSecond implements Runnable{
public void run() {
lock1.lock();
try {
System.out.println("lock2");
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}finally {
lock1.unlock();
}
}
}
private LockInitFirst getLockInitFirst(){
LockInitFirst lif = new LockInitFirst();
return lif;
}
private LockInitSecond getLockInitSecond(){
LockInitSecond lis = new LockInitSecond();
return lis;
}
public static void main(String[] args) {
LockThread lt = new LockThread();
// LockInitFirst lifirst = lt.new LockInitFirst();可以用这种方式new出一个内部类
Thread th1 = new Thread(lt.getLockInitFirst());
Thread th2 = new Thread(lt.getLockInitSecond());
th1.start();
th2.start();
}
}
线程学习二,ReentrantLock.Lock实现线程互斥
最新推荐文章于 2022-04-20 07:16:36 发布