如何在JAVA中减慢线程速度

时间:2012-06-18 19:07:12

标签: java multithreading

我有这个类,我在其中运行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();
    }    
}

请帮忙

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

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

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

    首先,我不明白什么是神奇的“如果你在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...
    

答案 2 :(得分:0)

我添加了一个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();
}    
}