Reputation: 14707
I have the following Java program:
public class A extends Thread {
int count;
@Override
public void run() {
while (true)
count++;
}
public static void main(String...strings){
A obj = new A();
obj.start();
System.out.println("The value of count is " + obj.count);
}
}
When running this program the output is: The value of count is 0
(and the program stays running). As far as my understanding with thread it should run in an infinite loop and never print 0. Could anyone help me understanding the nature of this program.
Upvotes: 2
Views: 80
Reputation: 285450
The thread starts at about the same time as the System.out.println runs, and since the thread is background, the println does not wait for it to run, and so you are seeing the initial value of count.
Also as an aside, the count variable should be declared volatile to ensure that the main thread sees changes to the variable made in the loop thread.
Upvotes: 4
Reputation: 754
Wouldn't the System.out call only run once?
I would put the System.out.println call inside the while loop.
Its probably better to use a getter/setter method for count
and make sure only one or the other can access the variable at any given time.
Upvotes: 0
Reputation: 29266
The "thread" isn't doing the print, your main is. What were you expecting to happen?
You should also use some kind of protection so both threads can safely access the variable.
Upvotes: 1