简体   繁体   中英

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

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

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:

  1. Use Thread.join (as suggested by @Suraj Chandran but his reply seems to have been deleted)
  2. Use a CountDownLatch (as also suggested by @zaske)
  3. Use 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. But, to use Thread.join() from your main code, the code would look like

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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