简体   繁体   中英

Java Thread doesn't work when trying to change variable value

I'm experimenting a bit with Java Threads and I'm trying to use a Thread to change some variable called number in my class by a Thread in another class.
But apparently it is not working, I always get the 0 from when I started my value, maybe somebody could tell me why.

This is my first class:

public class ThreadTest {
    public int number = 0;

    public static void main(String[] args) {
        ThreadTest Adding = new ThreadTest();
        Adding.addingOnes();
        System.out.println(Adding.number);
    }

    public void addingOnes() {
        Runnable thread1 = new ThreadClassPlus();
        Thread t1 = new Thread(thread1);
        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void add() {
        number++;
    }
}

And my second class for the Thread:

public class ThreadClassPlus extends ThreadTest implements Runnable {
    public void run() {
        for(int i = 0; i < 10000; i++) {
            add();
        }
    }
}

The problem is that your ThreadTest instance and your ThreadClassPlus instance are different objects. Your thread is incrementing number in the latter instance, but your main method is reading the value of number from the former. Naturally, the former doesn't have the value of the latter.

The threading is working fine. The problem is in how you are using it.

Here is a corrected version:

public class ThreadTest implements Runnable {

    public int number = 0;

    public static void main(String[] args) {
        ThreadTest adding = new ThreadTest();
        adding.addingOnes();
        System.out.println(adding.number);
    }

    public void addingOnes()
        Thread t1 = new Thread(this);
        t1.start();
        try {
            t1.join();
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void add() {
        number++;
    }

    public void run() {
        for(int i = 0; i < 10000; i++) {
            add();
        }
    }
}

Please note carefully the various style changes I made. Java style is important.

Simply because you are increasing value of variable number belonging to object thread1 , while printing value of variable number belonging to object Adding .

Just printout proper variable value and you will see expected result:

    System.out.println(((ThreadClassPlus)thread1).number);

And BTW, please, do not name variables starting with uppercase, this is very bad style: A dding => a dding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM