Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slow a thread down in JAVA

I have this class in which I run a for loop 10 times. This class implements Runnable interface. Now in main() I create 2 threads. Now both will run loop till 10. But I want to check loop count for each thread. If t1 is past 7 then make it sleep 1 second so as to let t2 complete. 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

like image 262
Shades88 Avatar asked Jun 18 '12 19:06

Shades88


1 Answers

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. 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).

like image 98
Yair Zaslavsky Avatar answered Oct 03 '22 09:10

Yair Zaslavsky