Discuss / Java / “完整的例子”中有一处不懂,求解答

“完整的例子”中有一处不懂,求解答

Topic source

Allwritten

#1 Created at ... [Delete] [Delete and Lock User]

请问:

第5行

for (int i=0; i<5; i++) {

创建5遍 线程t 的意义是什么?我的理解是第9行while(true)已经确保了 线程t 始终在运行。

我将第5行的for循环去掉,后面 t的中断 中也将for循环去掉,运行结果与原始版本相同。

5个t线程都在等待获取task,1个add线程在不断放入task(10次)。

你把   System.out.println("execute task: " + s)    改成     System.out.println(this.getName() + " execute task: " + s)  就可以看到是不同的线程在执行task。

意公子-

#3 Created at ... [Delete] [Delete and Lock User]

请问关于中断的使用,是否存在问题

在阻塞状态下发生中断时,才会抛出InterruptedException异常

在非阻塞状态下中断时,仅仅它的中断状态会被设置,并不会触发InterruptedException异常

所以编译无法通过,会提示:Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body。

5个线程是为了模拟真实的项目场景,真实场景下通常会有多个消费者。

我就说呢,这个5和下面的10思考了好久,莫非是有什么关系,原来只是模拟实际情况

fqjx

#6 Created at ... [Delete] [Delete and Lock User]

2楼说的打印线程名字,不能用this,而要用

Thread.currentThread().getName()

yingying1489

#7 Created at ... [Delete] [Delete and Lock User]

5遍的意义是模拟一种场景有5个线程去取值,而实际上的运用中这种场景是很常见的。


  • 1

Reply