竞态条件示例:
public class Client {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable, "线程1");
Thread thread2 = new Thread(myRunnable, "线程2");
Thread thread3 = new Thread(myRunnable, "线程3");
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
System.out.println(myRunnable.getA());
}
}
class MyRunnable implements Runnable {
private int a = 0;
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
++a;
}
}
public int getA() {
return a;
}
}
输出结果不一定,与预期不符。
解决方案1:内置锁,synchronized
解决方案2:显示锁,lock。unlock要放在finally里。