标签:
JDK内部提供了大量的API和框架,这里主要介绍三部分
在代码中,类ReenterLock实现了Runnable,其中有static的变量i,在run()方法中会对i进行自增操作。
自增操作的步骤为:get-set,先获取值再增加值。
如果在这里不进行控制的话,会导致get的值不是最新set的值。
因此,在自增的时候使用锁进行控制,保证get-set操作的时候只有一个线程操作。
package com.tuniu.concurrency;
import java.util.concurrent.locks.ReentrantLock;
public class Lock {
public static void main(String[] args) {
ReenterLock lock = new ReenterLock();
Thread t1 = new Thread(lock);
Thread t2 = new Thread(lock);
t1.start();
t2.start();
}
}
class ReenterLock implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
public static int i = 0;
public void run() {
for (int j = 0; j<1000; j++) {
lock.lock();
try {
i++;
} finally {
lock.unlock();
}
}
}
}标签:
原文地址:http://www.cnblogs.com/jiejiecool/p/5914682.html