假设我有一个线程正在运行,我想让它等待,然后被中断,以便它将再次运行。然而,对于我的作业,我不允许为我的方法使用Synchronized
标记。是否有另一种方法,我可以做我想要使用wait()
或可能另一个内置方法?还是比这更复杂?谢谢!
public void run()
{
int counter = 0;
Thread t = new Thread();
while(counter < 1){
sleepTime = generator.nextInt((3000-200)+1)+200;
withdrawAmount = generator.nextInt(50-1+1)+1;
balance = BalanceCall.getBalance();
if ((balance - withdrawAmount) > 0){
t.interrupt();
balance = BalanceCall.updateBalance(withdrawAmount, "Withdraw");
System.out.print(" " + threadName + " withdraws $" + withdrawAmount + " Balance is $" + balance + "n");
}
else{
System.out.print(" " + threadName + " withdraws $" + withdrawAmount + " Withdrawal - Blocked - Insufficient Fundsn");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
} // end method run
您可以使用Thread.sleep(Long.MAX_VALUE)
。线程。Sleep方法休眠给定毫秒数。Long.MAX_VALUE
毫秒实际上是无限的(数亿年)。但是睡眠会被Thread.interrupt()
打断。