huzaifa imran
huzaifa imran

Reputation: 45

Why does the value of variable in a thread remains constant despite the thread running?

I am new to threading concepts in Java. I made a thread consisting of a method called timer() this method lessens the value of the variable 'time'. I dont know what I am doing wrong in this, The code is posted below:

package Threading;
/**
 * Threads are used to perform tasks cocurrently 
 * In this example we used Thread Class 
 * .start() is method use to run the method
 * .sleep is used for delay and so on
 */
public class Intro_using_Thread extends Thread {
    int time;


    public Intro_using_Thread(int time) {
        this.time = time;
    }
    

    public void timer() {
        for (int i = time; i >= 0; i--) {
            time--;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Driver Class

package Threading;

import java.util.Scanner;

/**
 * Threads are used to perform tasks cocurrently In this example we used Thread
 * Class .start() is method use to run task
 */
public class Intro_using_thread_run {
    public static void main(String[] args) {
        int choice;
        Scanner in = new Scanner(System.in);
        Intro_using_Thread timerobj = new Intro_using_Thread(200000);
        timerobj.start();
        while (timerobj.time!=0) {
            choice = in.nextInt();
            System.out.println("The time is = "+timerobj.time);
            
        }
    }
    
}

OUTPUT

The Output is in this link

I dont know why Stack overflow does not lemme add pictures.

Upvotes: 0

Views: 87

Answers (1)

Akshar
Akshar

Reputation: 121

The start() method causes the thread to begin execution. JVM calls the run() method of the newly started thread. So you have to rename timer() function to run().

package Threading;
/**
 * Threads are used to perform tasks cocurrently 
 * In this example we used Thread Class 
 * .start() is method use to run the method
 * .sleep is used for delay and so on
 */
public class Intro_using_Thread extends Thread {
    int time;


    public Intro_using_Thread(int time) {
        this.time = time;
    }
    

    public void run() {
        for (int i = time; i >= 0; i--) {
            time--;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Update : Edited the explanation to be more clear.

Upvotes: 3

Related Questions