我有以下代码:
import java.security.SecureRandom;
public class Producer implements Runnable
{
private static final SecureRandom generator = new SecureRandom();
private final Buffer sharedLocation; // reference to shared object
// constructor
public Producer(Buffer sharedLocation)
{
this.sharedLocation = sharedLocation;
}
// store values from 1 to 10 in sharedLocation
public void run()
{
int sum = 0;
for (int count = 1; count <= 10; count++)
{
try // sleep 0 to 3 seconds, then place value in Buffer
{
Thread.sleep(generator.nextInt(3000)); // random sleep
sharedLocation.blockingPut(count); // set value in buffer
sum += count; // increment sum of values
System.out.printf("\t%2d%n", sum);
}
catch (InterruptedException exception)
{
Thread.currentThread().interrupt();
}
}
System.out.printf(
"Producer done producing%nTerminating Producer%n");
}
} // end class Producer
我不明白它的“try-catch”部分: 是不是方法sleep()将抛出InterruptedException(),因此try块将终止并且catch块将执行? 然后我们如何在try块中的sleep()语句之后编写语句,即。他们不能正确执行?
答案 0 :(得分:1)
当Thread.sleep
正常完成时,将执行任何后续语句。只有当线程在sleep
之前或期间被中断时,这些语句才会被执行。
请注意,try / catch应该在循环周围:因为Thread.currentThread().interrupt()
,因为Thread.currentThread().interrupt()
,下一次循环迭代的睡眠将立即中断,然后你调用try {
for (int count = 1; count <= 10; count++)
{
Thread.sleep(generator.nextInt(3000)); // random sleep
// ...
}
} catch (InterruptedException exception) {
Thread.currentThread().interupt();
}
,在下一个循环迭代中睡眠将立即中断,等等。
一旦中断,你也可以放弃循环:
cld2