竞态条件:多个线程共享的资源就是竞态资源。例如:多个线程操作同一个变量。
临界区:共享变量所在的那块代码就是临界区
package com.concurenny.chapter.three;
/**
* 创建者:Mr lebron 创建时间:2017年11月16日 下午4:11:53
* count是被两个线程共享的,所以是竞态资源。对count的操作是在add方法,所以add方法就是临界区
*/
public class RaceConditionDemo {
public static void main(String[] args) throws InterruptedException {
final Counter counter = new Counter();
// java8 lambda表达式实现
new Thread(() -> {
System.out.println(counter.add(1));
}).start();
new Thread(() -> {
System.out.println(counter.add(12));
}).start();
}
static class Counter {
private int count = 0;
public int add(int plus) {
return this.count += plus;
}
}
}