Java中String.intern在多线程环境中的用法

private static void multiThreadedLocalPoolTest( final int cnt ) throws InterruptedException {
    final Runnable task1 = new Runnable() {
        @Override
        public void run() {
            final List<String> lst = new ArrayList<String>( 100 );
            long start = System.currentTimeMillis();
            for ( int i = 0; i < cnt; ++i )
            {
                final String str = Integer.toString( i );
                final String interned = str.intern();
                if ( str != interned )
                    System.out.println( "Thread 0: different interned " + str );
                lst.add( interned );
                if ( i % 1000000 == 0 )
                {
                    System.out.println( "Thread 0 : " + i + "; time = " + ( System.currentTimeMillis() - start ) / 1000.0 + " sec" );
                    start = System.currentTimeMillis();
                }
            }
        System.out.println( "Total length = " + lst.size() );
        }
    };
 
    final Runnable task2 = new Runnable() {
    @Override
    public void run() {
        final List<String> lst = new ArrayList<String>( 100 );
        long start = System.currentTimeMillis();
        for ( int i = 0; i < cnt; ++i )
        {
            final String str = Integer.toString( i );
            final String interned = str.intern();
            if ( str == interned )
                System.out.println( "Thread 1: same interned " + str );
            lst.add( interned );
            if ( i % 1000000 == 0 )
            {
                System.out.println( "Thread 1 : " + i + "; time = " + ( System.currentTimeMillis() - start ) / 1000.0 + " sec" );
                start = System.currentTimeMillis();
            }
        }
        System.out.println( "Total length = " + lst.size() );
    }
};
 
final Thread thread1 = new Thread( task1 );
thread1.start();
 
Thread.sleep( 2000 );
 
final Thread thread2 = new Thread( task2 );
thread2.start();}

 

你可能感兴趣的:(String)