public class CountTest {
private static int x =0;
// 计数方法
public void count() {
for(int i=0;i<=100;i++) {
x = x+i;
}
System.out.println(Thread.currentThread().getName()+"--"+x);
}
public static void main(String[] args) {
// 定义线程实现接口
Runnable runnable = new Runnable(){
CountTest counter = new CountTest ();
@Override
public void run() {
counter.count();
}
};
Thread thread1 = new Thread(runnable, "线程1");
Thread thread2 = new Thread(runnable, "线程2");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("最终x的值:"+x);
}
}
输出结果1:
线程2--7900
线程1--7900
最终x的值:7900
输出结果2:
线程2--10100
线程1--10100
最终x的值:10100
输出结果3:
线程1--5050
线程2--10100
最终x的值:10100
总结:
1.由于count
没有增加关键字synchronized
,所以最终结果只能是小于等于两线程各自和之和。
2.假设在变量x
之前加volatile
关键字,会怎么样呢?
volatile
的属性:a.可见性;b.禁止指令重排;c.不保证原子性。
由于a、c性质的存在,猜测会在原来的基础上会很靠近两线程各自和之和。