简体   繁体   English

如何在JAVA中减慢线程速度

[英]How to slow a thread down in JAVA

I have this class in which I run a for loop 10 times. 我有这个类,我在其中运行10次for循环。 This class implements Runnable interface. 该类实现了Runnable接口。 Now in main() I create 2 threads. 现在在main()中我创建了2个线程。 Now both will run loop till 10. But I want to check loop count for each thread. 现在两个都将循环运行到10.但我想检查每个线程的循环计数。 If t1 is past 7 then make it sleep 1 second so as to let t2 complete. 如果t1超过7,则让它休眠1秒,以便让t2完成。 But how to achieve this? 但是如何实现这一目标呢? Please see the code. 请参阅代码。 I attempted but looks totally foolish. 我尝试但看起来完全愚蠢。 Just how to check the data of a thread ??? 只是如何检查一个线程的数据???

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

Please help 请帮忙

You should use some synchronization object, and not rely on slowing down of threads. 您应该使用一些同步对象,而不是依赖于减慢线程。 I strongly suggest you take a look at one of the classes at java.util.concurrent package. 我强烈建议你看一下java.util.concurrent包中的一个类。 You can use for this CountdownLatch - thread 1 will await on it, and thread 2 will perform the countdown and release the lock, and let thread 1 continue (the release should be done at the end of thread 2 code). 您可以使用此CountdownLatch - 线程1将等待它,线程2将执行倒计时并释放锁定,并让线程1继续(释放应在线程2代码结束时完成)。

If the goal is to run 2 Runnables in parallel (as Threads) and wait for them both to finish, you can, in increasing order of complexity/power: 如果目标是并行运行2个Runnables(作为Threads)并等待它们两者完成,你可以按照复杂性/功能的递增顺序:

  1. Use Thread.join (as suggested by @Suraj Chandran but his reply seems to have been deleted) 使用Thread.join(由@Suraj Chandran建议,但他的回复似乎已被删除)
  2. Use a CountDownLatch (as also suggested by @zaske) 使用CountDownLatch(也由@zaske建议)
  3. Use ExecutorService.invokeAll() 使用ExecutorService.invokeAll()

EDIT ADDED 编辑增加

First, I don't understand what the magic "if you are at 7 then wait for the other" logic is all about. 首先,我不明白是什么魔法“如果你在7然后等待另一个”的逻辑就是这样。 But, to use Thread.join() from your main code, the code would look like 但是,要从主代码中使用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...

I added a synchronized Block, which can be entered by one thread at a time. 我添加了一个synchronized块,一次可以由一个线程输入。 Both threads call and enter the method parallel. 两个线程都调用并输入并行方法。 One thread will win the race and take the lock. 一个线程将赢得比赛并获得锁定。 After the first thread leaves the block it waits 2 seconds. 在第一个线程离开块后,它等待2秒。 In this time the second thread can iterate over the loop. 在这个时候,第二个线程可以遍历循环。 I think this behaviour is wanted. 我认为这种行为是必要的。 If the second thread must not wait 2 seconds, too, you can set some boolean flag, that the first thread finished the block and use this flag in an if statement, which prevents the wait time of the second thread. 如果第二个线程也不能等待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