T
Timo Nentwig
Hi!
I do start 10 threads in a loop and want only 2 to be running at once.
That works but I want pool.execute() to not return and therefore block
the for loop if there are already 2 threads running. How am I going to
do this?
Timo
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
class ConcurrentTest
{
private final ThreadPoolExecutor pool;
public ConcurrentTest()
{
pool = (ThreadPoolExecutor)Executors.newFixedThreadPool( 2 );
go();
}
public void go()
{
for( int i = 0; i < 10; i++ )
{
System.out.println( "start: " + i );
pool.prestartAllCoreThreads();
pool.execute( new Handler( new Integer( i ) ) );
System.out.println( "\tcore:" + pool.getCorePoolSize() + " active: "
+ pool.getActiveCount() + " completed:"
+ pool.getCompletedTaskCount() );
}
}
public static void main( String[] args )
{
new ConcurrentTest();
}
}
class Handler implements Runnable
{
private final Integer id;
public Handler( Integer id )
{
this.id = id;
}
public void run()
{
System.out.println( id );
for( int i = 0; i < 10000; i++ )
for( int j = 0; j < 10000; j++ );
System.out.println( id + " done" );
}
}
I do start 10 threads in a loop and want only 2 to be running at once.
That works but I want pool.execute() to not return and therefore block
the for loop if there are already 2 threads running. How am I going to
do this?
Timo
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
class ConcurrentTest
{
private final ThreadPoolExecutor pool;
public ConcurrentTest()
{
pool = (ThreadPoolExecutor)Executors.newFixedThreadPool( 2 );
go();
}
public void go()
{
for( int i = 0; i < 10; i++ )
{
System.out.println( "start: " + i );
pool.prestartAllCoreThreads();
pool.execute( new Handler( new Integer( i ) ) );
System.out.println( "\tcore:" + pool.getCorePoolSize() + " active: "
+ pool.getActiveCount() + " completed:"
+ pool.getCompletedTaskCount() );
}
}
public static void main( String[] args )
{
new ConcurrentTest();
}
}
class Handler implements Runnable
{
private final Integer id;
public Handler( Integer id )
{
this.id = id;
}
public void run()
{
System.out.println( id );
for( int i = 0; i < 10000; i++ )
for( int j = 0; j < 10000; j++ );
System.out.println( id + " done" );
}
}