繁体   English   中英

如何在JAVA中减慢线程速度

[英]How to slow a thread down in JAVA

我有这个类,我在其中运行10次for循环。 该类实现了Runnable接口。 现在在main()中我创建了2个线程。 现在两个都将循环运行到10.但我想检查每个线程的循环计数。 如果t1超过7,则让它休眠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代码结束时完成)。

如果目标是并行运行2个Runnables(作为Threads)并等待它们两者完成,你可以按照复杂性/功能的递增顺序:

  1. 使用Thread.join(由@Suraj Chandran建议,但他的回复似乎已被删除)
  2. 使用CountDownLatch(也由@zaske建议)
  3. 使用ExecutorService.invokeAll()

编辑增加

首先,我不明白是什么魔法“如果你在7然后等待另一个”的逻辑就是这样。 但是,要从主代码中使用Thread.join(),代码看起来就像

t1.start();  // Thread 1 starts running...
t2.start();  // Thread 2 starts running...

t1.join();   // wait for Thread 1 to finish
t2.join();   // wait for Thread 2 to finish

// from this point on Thread 1 and Thread 2 are completed...

我添加了一个synchronized块,一次可以由一个线程输入。 两个线程都调用并输入并行方法。 一个线程将赢得比赛并获得锁定。 在第一个线程离开块后,它等待2秒。 在这个时候,第二个线程可以遍历循环。 我认为这种行为是必要的。 如果第二个线程也不能等待2秒,你可以设置一些布尔标志,第一个线程完成块并在if语句中使用这个标志,这可以防止第二个线程的等待时间。

class SimpleJob implements Runnable {
int i;
public void run(){

    synchronized (this) {
        for(i=0; i<8; i++){
            System.out.println(Thread.currentThread().getName()+" Running ");
        } 
    } 

    try {
        System.out.println("Here");
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    for(i=0; i<2; 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();
    t2.start();
}    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM