【发布时间】:2014-12-01 06:11:04
【问题描述】:
我目前正在从一本书中阅读有关 Java Consumer-Producer 解决方案的实现。
public class Producer extends Thread {
private IntBuffer buffer;
public Producer( IntBuffer buffer ){
this.buffer = buffer;
}
public void run(){
Random r = new Random();
while( true ){
int num = r.nextInt();
buffer.add( num );
System.out.println( “Produced “ + num );
}
}
}
public class Consumer extends Thread {
private IntBuffer buffer;
public Consumer( IntBuffer buffer ){
this.buffer = buffer;
}
public void run(){
while( true ){
int num = buffer.remove();
System.out.println( “Consumed “ + num );
}
}
}
public class IntBuffer {
private int index;
private int[] buffer = new int[8];
public void add( int num ){
while( true ){
if( index < buffer.length ){
buffer[index++] = num;
return;
}
}
}
public int remove(){
while( true ){
if( index > 0 ){
return buffer[--index];
}
}
}
}
IntBuffer b = new IntBuffer();
Producer p = new Producer( b );
Consumer c = new Consumer( b );
p.start();
c.start();
我有几个问题:
根据本书,此方法使用忙等待。这发生在哪里?据我所知,当一个线程正在等待另一个线程完成其执行才能恢复自己的执行时,就会发生忙碌等待。通过使用 wait() 方法,从技术上讲,线程是否仍然等待到 notify() 调用?
为什么同步添加/删除方法不能解决访问控制问题?我认为同步一词会阻止多个线程访问同一代码段。
为什么 add/remove 方法中都有一个 while(true) 循环?
【问题讨论】:
-
您的
3回答您的1。 -
@SotiriosDelimanolis -
while( true )不只是等待吗?我的意思是他不是在等待任何条件成真.. -
@TheLostMind
if中的条件while。注意每个return。 -
它只是在等待,是的,但也阻止方法返回,直到 if() 语句中的条件变为真,此时 then 子句从 while 循环和方法中返回。
-
@SotiriosDelimanolis - 啊。我没有正确看到
if条件。谢谢:)
标签: java multithreading concurrency thread-safety