【问题标题】:Why does the value of variable in a thread remains constant despite the thread running?为什么尽管线程正在运行,但线程中变量的值仍然保持不变?
【发布时间】:2021-02-09 14:24:32
【问题描述】:

我是 Java 线程概念的新手。我创建了一个由名为 timer() 的方法组成的线程,该方法减少了变量“time”的值。我不知道我在这做错了什么,代码贴在下面:

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();
            }
        }
    }
}

驱动类

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);
            
        }
    }
    
}

输出

The Output is in this link

我不知道为什么堆栈溢出不让我添加图片。

【问题讨论】:

    标签: java multithreading oop


    【解决方案1】:

    start() 方法使线程开始执行。 JVM 调用新启动线程的 run() 方法。 所以你必须将 timer() 函数重命名为 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();
                }
            }
        }
    }
    

    更新:编辑解释更清楚。

    【讨论】:

    • Re,“当您调用 ...start() 时,它...调用 run()。”这是真的,但这样说可能会误导初学者。 run() 调用发生因为start() 调用,但它不会发生内部start() 调用:它发生在不同的线程中。
    • 这是否意味着简单地调用 timerobj.run() 将在同一个线程上运行该函数?这是否意味着在运行 start() 一次后会创建一个不同的线程,之后每个 run() 都会调用该新线程?
    • 所罗门:更新了答案以更清楚。
    • huzaifa : A) 这是否意味着简单地调用 timerobj.run() 将在同一个线程上运行该函数? - 是的。 timerobj 仍然是一个 java 对象,您可以调用它的函数。 B)这是否意味着在运行 start() 一次后会创建一个不同的线程,之后每个 run() 都会调用该新线程? -- start() 创建一个新线程并在新线程上调用 run() 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2021-02-12
    相关资源
    最近更新 更多