测试程序:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ReverseTest
{
@Test
public void testNormalSentence()
{
assertEquals( new ConcurrentReverse( "Hello Peter Sunny Leaf" ).reverse(), "Leaf Sunny Peter Hello" );
}
@Test
public void testEmptySentence()
{
assertEquals( new ConcurrentReverse( "" ).reverse(), "" );
}
@Test
public void testSpaceSentence()
{
assertEquals( new ConcurrentReverse( " " ).reverse(), " " );
}
@Test
public void testMultipleSpaceSentence()
{
assertEquals( new ConcurrentReverse( " 123 345 " ).reverse(), " 345 123 " );
}
@Test
public void testSentenceWithSpacePrefix()
{
assertEquals( new ConcurrentReverse( " 123 456" ).reverse(), "456 123 " );
}
@Test
public void testSentenceWithSpaceSuffix()
{
assertEquals( new ConcurrentReverse( "123 456 " ).reverse(), " 456 123" );
}
@Test
public void testSentenceWithSpaceDoubleEnded()
{
assertEquals( new ConcurrentReverse( " 123 , 456 " ).reverse(), " 456 , 123 " );
}
}
主程序:
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;
public class ConcurrentReverse
{
private final static char SEPERATOR = ' ';
private StringBuilder sentence;
private ForkJoinPool exetutor;
ConcurrentReverse( String sentence )
{
this.sentence = new StringBuilder( sentence );
this.exetutor = new ForkJoinPool();
}
class ReverseTask extends RecursiveAction
{
private static final long serialVersionUID = 1L;
private int from;
private int to;
ReverseTask( int from, int to )
{
this.from = from;
this.to = to;
}
@Override
protected void compute()
{
reverse_word( from, to );
}
}
/**
* Algorithm => reverse the whole String and then each word
*
* @return the reversed string
* @throws InterruptedException
*/
public String reverse()
{
// Reverse the whole string first, the internal string will be replace with the inverse one
sentence.reverse();
// Reverse each word separated by the SEPERATOR
for ( int j = 0, i = 0; j <= sentence.length(); j++ )
{
if ( j == sentence.length() || SEPERATOR == sentence.charAt( j ) )
{
if ( j != i )
{
exetutor.submit( new ReverseTask( i, j - 1 ) );
}
i = j + 1;
}
}
// Wait all tasks to finish word level inversion
try
{
exetutor.shutdown();
exetutor.awaitTermination( 1, TimeUnit.DAYS );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return sentence.toString();
}
private void reverse_word( int from, int to )
{
for ( ; from < to; from++, to-- )
{
swap( from, to );
}
}
private void swap( int a, int b )
{
char a_value = sentence.charAt( a );
char b_value = sentence.charAt( b );
sentence.setCharAt( a, b_value );
sentence.setCharAt( b, a_value );
}
}
阅读(1447) | 评论(0) | 转发(0) |