package com.hurricane.learn.concurrent;
public class App {
static int i = 0;
public static void main(String[] args) throws InterruptedException {
Runnable runnable = ()->{
for (int j = 0; j < 100000; j++) {
i++;
// 增加下面这一行打印,会使得最后的结果输出趋向正确
// System.out.println(Thread.currentThread().getName()+"---->"+i);
}
};
Thread t1 = new Thread(runnable, "t1");
Thread t2 = new Thread(runnable, "t2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
执行上面的代码,结果为:128843,可见并发带来了结果的误差。
ps.如上述代码中的注释所提到的在自加之后进行输出则结果是接近正确的199994。
解决上面的并发问题的方式:
- 将i++操作放在同步块中
synchronized (App.class) {
i++;
}
- 使用重入锁
package com.hurricane.learn.concurrent;
import java.util.concurrent.locks.ReentrantLock;
public class App {
static int i = 0;
static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Runnable runnable = ()->{
for (int j = 0; j < 100000; j++) {
lock.lock();
try {
i++;
} finally {
lock.unlock();
}
// 增加下面这一行打印,会使得最后的结果输出趋向正确
// System.out.println(Thread.currentThread().getName()+"---->"+i);
}
};
Thread t1 = new Thread(runnable, "t1");
Thread t2 = new Thread(runnable, "t2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
注意,将要进行的操作放到try包含的语句块中,虽然i++不会抛出什么异常,但这是标准操作,保证执行操作之后一定可以将锁释放掉。
神奇的是将代码改为如下的样子:
package com.hurricane.learn.concurrent;
public class App {
static Integer i = 0;
public static void main(String[] args) throws InterruptedException {
Runnable runnable = ()->{
for (int j = 0; j < 100000; j++) {
synchronized (i) {
i++;
}
// 增加下面这一行打印,会使得最后的结果输出趋向正确
// System.out.println(Thread.currentThread().getName()+"---->"+i);
}
};
Thread t1 = new Thread(runnable, "t1");
Thread t2 = new Thread(runnable, "t2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
仍存在并发问题,明明都对i进行加锁了。
猜测可能是线程对变量i的副本做的操作,于是加了volatile关键字:
static volatile Integer i = 0;
仍然有并发问题存在。