java多线程成员变量共享问题
程序员文章站
2022-05-02 13:12:31
...
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