示例1:线程不安全的计数器
public class AddCountDemo {
private int i = 0;
public static void main(String[] args) {
final AddCountDemo synchronizDemo = new AddCountDemo();
for (int j = 0; j < 500; j++) {
new Thread(new Runnable() {
@Override
public void run() {
synchronizDemo.addCount();
}
}).start();
}
// 使当前所有线程运行完成之后再运行以下代码
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println(synchronizDemo.i);
}
private void addCount() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.i++;
}
}
示例2:使用synchronized实现线程安全的计数器
public class AddCountSynchronizDemo {
private int i = 0;
public static void main(String[] args) {
final AddCountSynchronizDemo synchronizDemo = new AddCountSynchronizDemo();
for (int j = 0; j < 500; j++) {
new Thread(new Runnable() {
@Override
public void run() {
synchronizDemo.addCount();
}
}).start();
}
// 使当前所有线程运行完成之后再运行以下代码
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println(synchronizDemo.i);
}
private void addCount() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
this.i++;
}
}
}
示例3:使用ReentrantLock方式实现线程安全的计数器
import java.util.concurrent.locks.ReentrantLock;
public class AddCountReentrantDemo {
private int i = 0;
private ReentrantLock reentrantLock = new ReentrantLock();
public static void main(String[] args) {
final AddCountReentrantDemo synchronizDemo = new AddCountReentrantDemo();
for (int j = 0; j < 500; j++) {
new Thread(new Runnable() {
@Override
public void run() {
synchronizDemo.addCount();
}
}).start();
}
// 使当前所有线程运行完成之后再运行以下代码
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println(synchronizDemo.i);
}
private void addCount() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
reentrantLock.lock();
try {
this.i++;
} finally {
reentrantLock.unlock();
}
}
}
示例4:使用CAS自旋方式实现线程安全的计数器
import java.util.concurrent.atomic.AtomicInteger;
public class AddCountCASDemo {
private int i = 0;
private AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) {
final AddCountCASDemo synchronizDemo = new AddCountCASDemo();
for (int j = 0; j < 500; j++) {
new Thread(new Runnable() {
@Override
public void run() {
synchronizDemo.addCount();
}
}).start();
}
// 使当前所有线程运行完成之后再运行以下代码
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println(synchronizDemo.atomicInteger.get());
}
private void addCount() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//atomicInteger.compareAndSet()
for (; ; ) {
int i = atomicInteger.get();
boolean result = atomicInteger.compareAndSet(i, ++i);
if (result) {
break;
}
}
}
}
boolean result = atomicInteger.compareAndSet(i, ++i);
操作的时候会检查值有没有变化,如果没有发生变化则更新,而后返回true;如果操作值发生变化则返回false,程序在for循环中重新这些++i操作;