AtomicInteger 执行计算时,原子递增,可以不用锁,就能实现同步。^_^
public class MyTest {
private AtomicInteger a =new AtomicInteger(0);
//ReentrantLock reentrantLock = new ReentrantLock();
public void increment() {
//reentrantLock.lock();
while (a.intValue() <10) {
int aValue =a.incrementAndGet();
System.out.println(Thread.currentThread().getName() +" a : " + aValue);
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
//reentrantLock.unlock();
}
public static void main(String[] args) {
MyTest myTest =new MyTest();
Thread t1 =new Thread(new Runnable() {
@Override
public void run() {
myTest.increment();
}
},"t1");
Thread t2 =new Thread(new Runnable() {
@Override
public void run() {
myTest.increment();
}
},"t2");
t1.start();
t2.start();
}
}
网友评论