简体   繁体   中英

How to start new Thread to continue work when Sleep is called within a Thread in Java

I am creating a Thread calling a custom compare method within a class - FastestComparator.java

The Thread Class:

public class FastestComparatorThread extends Thread {

    private int valueToFind;
    private List<CustomNumberEntity> list;
    private FastestComparator fastComparator = new FastestComparator();
    private int result = 1;

    public FastestComparatorThread(int valueToFind, List<CustomNumberEntity> list) {
        this.valueToFind = valueToFind;
        this.list = list;
    }

    public int getResult() {
        return result;
    }

    @Override
    public void run() {
        for (CustomNumberEntity customNumberEntity : list) {
            try {
                synchronized(fastComparator) {
                    result = fastComparator.compare(valueToFind, customNumberEntity);
                    System.out.println(result);
                }
            } catch (NumberFormatException e) {}
        }
    }
}

The Compare Method has a Sleep function within it:

public int compare(int firstValue, CustomNumberEntity secondValue){
        Random random = new Random();
        int mSeconds = (random.nextInt(6)+5)*1000; //milliseconds
        int secondValueAsNumber = Integer.parseInt(secondValue.getNumber());
        try {
            Thread.sleep(mSeconds);
        } catch (InterruptedException e) {
            //error while sleeping. Do nothing.
        }
        return firstValue-secondValueAsNumber;
    }

Currently, after starting the Thread, I am calling the interrupt() method, while the Thread isAlive() essentially to avoid the sleep after starting the Thread

FastestComparatorThread fastestComparatorThread = new FastestComparatorThread(valueToFind, list);
fastestComparatorThread.start();

while(fastestComparatorThread.isAlive()) {
    fastestComparatorThread.interrupt();
    if (fastestComparatorThread.getResult() == 0) {
        return true;
    }
}

Is there a way of kicking off a new thread that continues the work when the first one sleeps instead of continuously interrupting the one Thread?

Is there a way of kicking off a new thread that continues the work when the first one sleeps...?

No. The Thread.sleep(nnnn) call does nothing. It does nothing for approximately nnnn milliseconds (but never less than nnnn milliseconds), and then it returns. There is no provision in Java for one thread to be automatically notified when some other thread calls sleep() .

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