为什么线程中变量的值保持不变,尽管线程运行?



我是Java中线程概念的新手。我做了一个线程,由一个叫做timer()的方法组成,这个方法减少了变量"时间"的值。我不知道我在这方面做错了什么,代码如下:

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

}
}

}

输出输出在这个链接

我不知道为什么Stack overflow不让我添加图片。

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

更新:编辑解释使其更清晰。

最新更新