public class IntSortReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> { private static final IntWritable lineNumber = new IntWritable(0); @Override protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { // ignore values: they'll always be 1 (as long as paired with IntMapper) synchronized (lineNumber) { /* TODO: Advance line number */ context.write(/* TODO: Write new, reduced <K,V> pair to context */); } } }
时间: 2024-02-10 13:05:22 浏览: 61
补全后的代码如下:
```
public class IntSortReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
private static final IntWritable lineNumber = new IntWritable(0);
private int count = 0;
@Override
protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// ignore values: they'll always be 1 (as long as paired with IntMapper)
synchronized (lineNumber) {
/* Advance line number */
count++;
lineNumber.set(count);
/* Write new, reduced <K,V> pair to context */
context.write(lineNumber, key);
}
}
}
```
在补全的代码中,我们通过使用 count 计数器和线程安全的 synchronized 关键字来实现了一个自增的 lineNumber,然后将新生成的键值对通过调用 context.write() 写入到 context 中。
阅读全文