- import
java.util.concurrent.atomic.AtomicBoolean; -
-
- public
class Lock { -
-
private AtomicBoolean lock = new AtomicBoolean(true); -
-
public boolean tryLock() { -
return lock.compareAndSet(true, false); -
} -
-
public void unlock() { -
lock.set(true); -
} -
- }
原理:CAS
优点:
适用场景:
我的应用场景:
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
private static long c = 0;
public static void main(String[] args) {
final Lock l = new Lock();
// final ReentrantLock l = new ReentrantLock();
Thread t1 = new Thread() {
public void run() {
for (int i = 0; i < 100000000;) {
if (l.tryLock()) {
c++;
i++;
l.unlock();
}
}
}
};
Thread t2 = new Thread() {
public void run() {
for (int i = 0; i < 100000000;) {
if (l.tryLock()) {
c++;
i++;
l.unlock();
}
}
}
};
long t = System.currentTimeMillis();
Thread t3 = new Thread() {
public void run() {
for (int i = 0; i < 100000000;) {
if (l.tryLock()) {
c++;
i++;
l.unlock();
}
}
}
};
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
}
System.out.println(c);
System.out.println(System.currentTimeMillis() - t);
}
}