[英]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我正在创建一个线程,在 class - FastestComparator.java 中调用自定义比较方法
The Thread Class:线程 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:比较方法里面有一个睡眠 function:
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目前,启动线程后,我调用的是interrupt()方法,而线程isAlive()本质上是为了避免启动线程后休眠
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.不。
Thread.sleep(nnnn)
调用什么都不做。 It does nothing for approximately nnnn
milliseconds (but never less than nnnn
milliseconds), and then it returns.它在大约
nnnn
毫秒(但绝不会少于nnnn
毫秒)内什么都不做,然后返回。 There is no provision in Java for one thread to be automatically notified when some other thread calls sleep()
. Java 中没有规定在其他线程调用
sleep()
时自动通知一个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.