大家请看代码和输出结果,我百思不得其解,为什么 amount只加了一次,开始我以为是static所致,就算去掉也还是有几率出现这样的结果,难道是多核cpu真的把两个线程同时执行了?
package study;
public class MyRunnable implements Runnable {
public static int amount=0;
@Override
public void run() {
// TODO 自动生成的方法存根
amount++;
String s=Thread.currentThread().getName();
System.out.println(s+" "+amount);
}
}
package study;
public class MyFirstThread {
public static void main(String[] args) {
// TODO 自动生成的方法存根
MyRunnable r1=new MyRunnable();
Thread AThread=new Thread(r1);
Thread BThread=new Thread(r1);
AThread.start();
BThread.start();
for(;;)
{
if((!AThread.isAlive())&&(!BThread.isAlive()))
{
System.out.println("amount ="+r1.amount);
break;
}
}
}
}