由于多个线程之间是抢占式执行的, 这就给调度执行顺序带来了随机性, 程序员需要在n多个调度执行顺序中保证每一个顺序最后执行的结果都是正确的, 如果其中有一个执行顺序出错, 则视为是出现bug, 即发生了线程安全问题
下面是一个有线程安全问题的代码:
package Thread;
class Add{
int a = 0;
public void add(){
for(int i = 0 ; i < 50000; i++){
a++;
}
}
}
public class ThreadDome11 {
public static void main(String[] args) {
Add a = new Add();
Thread t1 = new Thread(()->{
a.add();
});
Thread t2 = new Thread(()->{
a.add();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("最终值为:" + a.a);
}
}