为什么程序不打印 9 而打印 0?
AtomicInteger 也没有帮助(按照建议)
public class threadOne{
//Integer i=0;
AtomicInteger i=new AtomicInteger(0);
class firstThread implements Runnable{
AtomicInteger i;
firstThread(AtomicInteger i){
this.i=i;
}
public void run(){
while(i.intValue()<10){
i.incrementAndGet();
}
}
}
void runThread(){
Thread t = new Thread(new firstThread(i));
t.start();
System.out.println("Result : " + i.intValue());
}
public static void main(String[] args){
new threadOne().runThread();
}
}
最佳答案
记住:您正在打印 threadOne
的 i
,而不是 firstThread
两个类中的整数 i
彼此独立。其中一项的变化不会反射(reflect)在另一项上。 Integer
是一个不可变的类。
例如,
Integer i = 4;
Integer j = i;
j = 1; //same as j = new Integer(1);
System.out.println(i);
它打印 4
而不是 1
。同样的方式,firstThread
中的 i+=1
不会影响 threadOne
中的 i
,即您要执行的操作。正在打印。
您可以使用可变类,例如 AtomicInteger ,它会满足您的期望,或者简单地打印 firstThread
i
编辑:您需要等待线程执行完成才能看到更改。做
Thread t = new Thread(new firstThread(i));
t.start();
try{
t.join();
}catch(Exception e){}
System.out.println("Result : " + i.get());
关于java - 在线程中计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43949941/