请帮我为以下代码添加注释,并排版package T14; //Buffer.java public class Buffer { private int buffer = -1; // buffer缓冲区被producer 和 consumer 线程共享 private int occupiedBufferCount = 0; // 控制缓冲区buffers读写的条件边量 public synchronized void set( int value ) //place value into buffer { String name = Thread.currentThread().getName();//get name of thread that called this method // while there are no empty locations, place thread in waiting state while ( occupiedBufferCount == 1 ) { // output thread information and buffer information, then wait try { //System.err.println("Buffer full. "+ name + " waits." ); wait(); } // if waiting thread interrupted, print stack trace catch ( InterruptedException exception ) { exception.printStackTrace(); } } // end while buffer = value; // set new buffer value ++occupiedBufferCount; System.err.println(name + " writes " + buffer); notify(); // tell waiting thread to enter ready state } // end method set; releases lock on SynchronizedBuffer public synchronized int get() // return value from buffer { // for output purposes, get name of thread that called this method String name = Thread.currentThread().getName(); // while no data to read, place thread in waiting state while ( occupiedBufferCount == 0 ) { // output thread information and buffer information, then wait try { //System.err.println("Buffer empty. "+name + " waits." ); wait(); } catch ( InterruptedException exception ) { exception.printStackTrace(); } } // end while // indicate that producer can store another value , because consumer just retrieved buffer value --occupiedBufferCount; System.err.println( name + " reads " + buffer ); notify(); // tell waiting thread to become ready to execute return buffer; } // end method get; releases lock on SynchronizedBuffer }
时间: 2024-04-26 13:26:50 浏览: 82
// 该代码实现了一个Buffer类,用于控制producer和consumer线程对缓冲区的读写
package T14;
public class Buffer {
private int buffer = -1; // buffer缓冲区被producer和consumer线程共享
private int occupiedBufferCount = 0; // 控制缓冲区buffers读写的条件边量
// 将value存入缓冲区
public synchronized void set(int value) {
String name = Thread.currentThread().getName(); // 获取调用该方法的线程名称
// 当没有空位置时,将线程置于等待状态
while (occupiedBufferCount == 1) {
try {
//System.err.println("Buffer full. "+ name + " waits." );
wait();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
// 设置新的缓冲区值
buffer = value;
++occupiedBufferCount;
System.err.println(name + " writes " + buffer);
notify(); // 唤醒等待的线程
}
// 从缓冲区中取出值
public synchronized int get() {
String name = Thread.currentThread().getName(); // 获取调用该方法的线程名称
// 当没有数据可读时,将线程置于等待状态
while (occupiedBufferCount == 0) {
try {
//System.err.println("Buffer empty. "+name + " waits." );
wait();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
// 消费者已取出一个值,表示生产者可以再次存储一个值
--occupiedBufferCount;
System.err.println(name + " reads " + buffer);
notify(); // 唤醒等待的线程
return buffer;
}
}
阅读全文