Java Multithreading issue
I need to write a multi threaded version of the Sieve of Eratosthenes. I think I need to use a binary Semaphone for knowing when to kick off a new thread, but I also cant use busy waiting so I'm not sure.
I've written about 20 versions of this code and I cna't seem to get it to work. Here's what I have right now
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
publicclass testFilterimplements Runnable
{
privatevolatilestatic ArrayList<Integer> al =new ArrayList<Integer>();
privatevolatilestatic ArrayList<Integer> primes =new ArrayList<Integer>();
privatevolatilestatic LinkedBlockingQueue<Integer> lbq =new LinkedBlockingQueue<Integer>();
publicstaticvoid main(String[] args)throws Exception
{
init( 2000 );
sendThread();
Thread.sleep( 1000 );
print();
}
publicstaticsynchronizedvoid sendThread()
{
if ( !al.isEmpty() )
{
testFilter tf =new testFilter();
Thread thread =new Thread( tf );
int newPrime = al.remove( 0 );
lbq.add( newPrime );
primes.add( newPrime );
thread.start();
}
}
publicstaticvoid init(int size)
{
for (int i = 2; i <= size; i++ )
{
al.add( i );
}
}
publicstaticsynchronizedvoid print()
{
for (int i = 0; i < primes.size(); i++ )
{
System.out.println( primes.get( i ) );
}
}
publicvoid run()
{
boolean threadSent =false;
int remove = lbq.poll();
for (int i = 0; i < al.size(); i++ )
{
int current = al.get( i );
if ( current % remove == 0 )
{
if ( !threadSent )
{
al.remove( i );
threadSent =true;
}
sendThread();
}
}
}
}
Now this isn't working and I can't seem to figure out why. What I think I want to do it kick off a new thread as soon as the current thread has made a change to the List. This means that the first element in the list is a prime....I'm sure I'm missing something basic, any help would be greatly appreciated.
Message was edited by:
jstudent1986

