gpt4 book ai didi

java - Java中如何同步线程时间

转载 作者:行者123 更新时间:2023-11-30 11:06:44 25 4
gpt4 key购买 nike

我研究了一个线程并尝试使用线程制作一个计时器。给主线程写了一个时间

public class A {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, write the time in ms");
long time = Long.parseLong(reader.readLine());
B thread = new B();

int timer = 0;
try {
thread.start();
Thread.sleep(time);
timer=thread.stop();
}
catch(InterruptedException e) {
System.out.println("Oh....");
}
System.out.println("Result is "+timer);
}
}

并且每个毫秒程序在子线程中写入一个特定毫秒的名称。

public class B implements Runnable {

private volatile boolean running=true;
private int timer=0;
Thread thread;

public B() {
thread = new Thread(this);
}

public void run() {
while (running) {
System.out.println(timer);
timer++;
try {
Thread.sleep(1);
}
catch(InterruptedException e) {
System.out.println("B");
}
}
}
public int stop() {
running = false;
return timer;
}

public void start() {
thread.start();
}
}

但是当尝试使用参数 50 时得到结果 37。我想了解如何在时间上同步它。你能解释一下如何正确执行吗?

最佳答案

当时间结束时只要设置变量running为false,while循环就会结束,子线程也会结束。

所以在下一行之后,尝试将 running 变量设置为 false。(提供一些 setter 方法或可能在构造函数参数中)

Thread.sleep(time);

关于java - Java中如何同步线程时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29198259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com