计算一个线程

时间:2017-05-13 06:23:50

标签: java

为什么程序不能打印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();

    }

}

4 个答案:

答案 0 :(得分:1)

请记住:您正在打印i threadOne,而不是firstThread

两个章节中的Integer i 彼此独立。一个中的变化不会反映在另一个上。 Integer是一个不可变的类。

例如,

Integer i = 4;
Integer j = i;
j = 1; //same as j = new Integer(1);
System.out.println(i);

它会打印4而不是1。同样,i+=1中的firstThread不会影响i中的threadOne,这是您要打印的i

您可以使用可变类,例如AtomicInteger,它可以满足您的期望,或者只需打印firstThread的{​​{1}}

编辑:您需要等待线程的执行完成以查看更改。做

Thread t = new Thread(new firstThread(i));
t.start();
try{
    t.join();
}catch(Exception e){}
System.out.println("Result : " + i.get());

答案 1 :(得分:0)

因为声明,

System.out.println("Result : " + i);

指的是i类中的字段threadOne,而不是i类中增加的firstThread。在firstThread类中插入此语句以获得9。

做类似的事情,

    public void run(){
        while(i<10){
            i+=1;
        }
        // INSERT HERE
        System.out.println("Result : " + i);
    }   

答案 2 :(得分:0)

这是因为您声明了两个名为i的变量。

public class threadOne{
    Integer i=0; // <--- first one here
    class firstThread implements Runnable{
        Integer i; // <--- second one here
        firstThread(Integer i){
            this.i=i; // <--- here you are accessing the second one
        }
        public void run(){
            while(i<10){
                i+=1; // <--- here you are accessing the second one
            }
        }       
    }
    void runThread(){ 


        Thread t = new Thread(new firstThread(i)); // <--- here you are accessing the first one
        t.start();
        System.out.println("Result : " + i); // <--- here you are accessing the first one

    }
    public static void main(String[] args){
        new threadOne().runThread();    
    }

}

基本上发生的事情是你要打印出第一个i,而线程正在改变的是第二个i

要解决此问题,只需打印第二个i

firstThread first = new firstThread(i); // we need a firstThread variable because we need to access the second i later
Thread t = new Thread(first);
t.start();
System.out.println("Result : " + first.i);

答案 3 :(得分:0)

整数类是不可变的。 这意味着您无法从外部传递值并在方法内更改它而不返回新值!