Java多线程处理文本块重排时共享Char Buffer数组未正确更新问题
Let's break down exactly what's going wrong with your code, and how to fix it to get the expected "bcade" reordered output.
1. Critical Loop Condition Bug in Swapper.run()
This is the main reason only the first chunk is appearing in your final buffer. Look at your current loop:
for(int i = x; i < (y - x); i++) { buffer[offset + (i - x)] = content.charAt(i); }
The termination condition i < (y - x) is incorrect. For example, take the second interval (4,8): y - x equals 4, so your loop starts at i=4 and immediately checks 4 < 4—which is false. The loop never runs, so none of the other chunks get written to the buffer.
Fix the loop condition to iterate over the full range of the interval (from x to y):
@Override public void run() { int x = interval.getX(); int y = interval.getY(); // Iterate through every character in the interval [x, y) for(int i = x; i < y; i++) { // Calculate the position in the buffer: offset + within-chunk index buffer[offset + (i - x)] = content.charAt(i); } }
2. Intervals Array Doesn't Match the "bcade" Pattern
Your current intervals array is set to the original chunk order (0-4, 4-8, 8-12, ...), which doesn't implement the "bcade" reordering you need. The pattern translates to:
b= second chunk (original indices 4-8)c= third chunk (original indices 8-12)a= first chunk (original indices 0-4)d= fourth chunk (original indices 12-16)e= fifth chunk (original indices 16-20)
Update the intervals array in runSwapper() to match this order:
private static char[] runSwapper(String content, int chunkSize, int numChunks) { Interval[] intervals = new Interval[5]; // Match the "bcade" pattern intervals[0] = new Interval(4,8); // b intervals[1] = new Interval(8,12); // c intervals[2] = new Interval(0,4); // a intervals[3] = new Interval(12,16); // d intervals[4] = new Interval(16,20); // e char[] buffer = new char[content.length()]; Thread[] threads = new Thread[numChunks]; for(int i = 0; i < numChunks; i++) { Interval current = intervals[i]; threads[i] = new Thread(new Swapper(current, content, buffer, i * chunkSize)); threads[i].start(); } for(int i = 0; i < numChunks; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } return buffer; }
Why This Works
- With the fixed loop condition, every thread will now iterate over its entire assigned chunk and write all characters to the correct position in the shared buffer.
- The adjusted intervals array ensures each thread picks up the right original chunk and writes it to the target position defined by the "bcade" pattern.
After making these changes, running java TextSwap 4 letters.txt will produce your expected output: BBBBCCCCAAAADDDDEEEE.
内容的提问来源于stack exchange,提问作者HalfMillennium

