【发布时间】: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);
}
}
}
输出
我不知道为什么堆栈溢出不让我添加图片。
【问题讨论】:
标签: java multithreading oop