gpt4 book ai didi

java - 如何在 JAVA 中减慢线程速度

转载 作者:搜寻专家 更新时间:2023-10-31 19:48:18 25 4
gpt4 key购买 nike

我在这个类中运行了 10 次 for 循环。这个类实现了 Runnable 接口(interface)。现在在 main() 中我创建了 2 个线程。现在两者都将循环运行到 10。但我想检查每个线程的循环计数。如果 t1 超过 7,则让它 hibernate 1 秒,以便让 t2 完成。但是如何实现呢?请看代码。我试过了,但看起来很愚蠢。只是如何查看一个线程的数据???

class SimpleJob implements Runnable {
int i;
public void run(){
for(i=0; i<10; i++){
System.out.println(Thread.currentThread().getName()+" Running ");
}
}

public int getCount(){
return i;
}
}
public class Threadings {
public static void main(String [] args){
SimpleJob sj = new SimpleJob();
Thread t1 = new Thread(sj);
Thread t2 = new Thread(sj);

t1.setName("T1");
t2.setName("T2");

t1.start();
try{
if(sj.getCount() > 8){ // I know this looks totally ridiculous, but then how to check variable i being incremented by each thread??
System.out.println("Here");
Thread.sleep(2000);
}
}catch(Exception e){
System.out.println(e);
}
t2.start();
}
}

请帮忙

最佳答案

你应该使用一些同步对象,而不是依赖于线程的减慢。我强烈建议您看一下 java.util.concurrent 包中的其中一个类。您可以为此使用 CountdownLatch - 线程 1 将等待它,线程 2 将执行倒计时并释放锁,并让线程 1 继续(释放应在线程 2 代码的末尾完成)。

关于java - 如何在 JAVA 中减慢线程速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089401/

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