标签:++ 进入 因此 ring imp 高级功能 shu cas 关键字
package cas;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
public class MyThread extends Thread {
public static ReentrantLock lock = new ReentrantLock();
public static int i = 0;
public MyThread(String name) {
super.setName(name);
}
@Override
public void run() {
for (int j = 0; j < 100; j++) {
lock.lock();
try {
System.out.println(this.getName() + " " + i);
i++;
} finally {
lock.unlock();
}
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
MyThread test1 = new MyThread("thread1");
MyThread test2 = new MyThread("thread2");
test1.start();
test2.start();
test1.join();
test2.join();
System.out.println(i);
}
}
public static ReentrantLock lock = new ReentrantLock();
public TryLockTest(String name){
super(name);
}
@Override
public void run() {
try {
if (lock.tryLock(5, TimeUnit.SECONDS)) {
Thread.sleep(6000);
} else {
System.out.println(this.getName() + " get lock failed");
}
} catch (Exception e) {
} finally {
if (lock.isHeldByCurrentThread()) {
System.out.println("lock.isHeldByCurrentThread: " + this.getName());
lock.unlock();
}
}
}
public static void main(String[] args) {
TryLockTest t1 = new TryLockTest("TryLockTest1");
TryLockTest t2 = new TryLockTest("TryLockTest2");
t1.start();
t2.start();
}
}
##### 实现ReentrantLock公平锁
- 一般意义上的锁是不公平的,不一定先来的线程能先得到锁,后来的线程就后得到锁。不公平的锁可能会产生饥饿现象。
- 公平锁的意思就是,这个锁能保证线程是先来的先得到锁。虽然公平锁不会产生饥饿现象,但是公平锁的性能会比非公平锁差很多。
- synchronized是作为Java关键字是依赖于JVM实现,Java团队应该是优先考虑性能问题,因此synchronized是非公平锁。
- 使用方法:
public ReentrantLock(boolean fair)
public static ReentrantLock fairLock = new ReentrantLock(true);
```
标签:++ 进入 因此 ring imp 高级功能 shu cas 关键字
原文地址:https://www.cnblogs.com/frankltf/p/10345355.html