0

Recently I played around with multi threading a bit, and tried let multiple threads work on the same thing, but only continue with the execution of my programm once all threads are done. My code is way too slow (it should be way faster that it actually is) and I want to know if there is maybe a more efficient and faster way to achieve this:

My runnable class. For a certain task there needs to be a new Runnable which extends this Runnable and overwrites doTask().

public abstract class ParallelCappedRunnable implements Runnable {

private final Lock lock;
private final Condition condition;
private final ParallelCappedMultithreader pcm;

public ParallelCappedRunnable(ParallelCappedMultithreader pcm, Lock lock, Condition condition) {
    this.lock = lock;
    this.condition = condition;
    this.pcm = pcm;
}

@Override
public final void run() {
    doTask();
    pcm.sendSignal();
    if(pcm.getMissingSignals() == 0) {
        lock.lock();
        try {
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
}

public abstract void doTask();
}

This class starts many new threads which all work on the same task as soon as someone calls start() and "the call is over" (idk how to call this) as soon as every thread is done.

public class ParallelCappedMultithreader {

private AtomicInteger missingSignals = new AtomicInteger (0);
private final int MAX_THREADS;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private final Class runnable, parentClass;
private final Object parentInstance;

public ParallelCappedMultithreader(Class<? extends ParallelCappedRunnable> runnable, int threads, Class parentClass, Object parentInstance) {
    this.runnable = runnable;
    this.parentClass = parentClass;
    this.MAX_THREADS = threads;
    this.parentInstance = parentInstance;
}
public ParallelCappedMultithreader(Class<? extends ParallelCappedRunnable> runnable, int threads) {
    this(runnable, threads, null, null);
}


public void start() throws InterruptedException{
    try {
        missingSignals.set(MAX_THREADS);
        Constructor constructor;
        if(parentClass == null) {
            constructor = runnable.getDeclaredConstructor(ParallelCappedMultithreader.class, Lock.class, Condition.class);
        }
        else {
            constructor = runnable.getDeclaredConstructor(parentClass, ParallelCappedMultithreader.class, Lock.class, Condition.class);
        }
        for(int i = 0; i < MAX_THREADS; i++) {
            if(parentClass == null)
                (new Thread((Runnable)constructor.newInstance(this, lock, condition))).start();
            else 
                (new Thread((Runnable)constructor.newInstance(parentInstance, this, lock, condition))).start();
        }
    } catch (Exception ex) {
        Logger.getLogger(ParallelCappedMultithreader.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(0);
    }
    lock.lock();
    try {
        condition.await();
    } finally {
        lock.unlock();
    }
}

public int getMissingSignals() {
    return missingSignals.get();
}

public void sendSignal() {
    System.out.println(missingSignals.getAndDecrement());

}
}
2
  • 1
    I think you need to look at Java's ExecutorService Apr 16, 2014 at 21:39
  • It looks like you're trying to reimplement Thread.join(), or CountDownLatch. Read their javadoc.
    – JB Nizet
    Apr 16, 2014 at 21:43

2 Answers 2

0

Have you tried thread.join()?

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join%28%29

Basically you can start as many threads as you want, and the "parent" waits for the "child" thread to die by calling thread join() on it before continuing.

Java: How to use Thread.join

0

you've got too many things going on (and what's with all the reflection). You can use join to wait for a single thread. If you want to wait for multiple threads, you could do something like this:

MyRunnable(List threads) {
    lock (threads) {
        threads.add(this);
    }
}

void run() {
    doStuff()

    lock (threads) {
        threads.remove(this);

        if (threads.size() == 0)
            threads.notify();
    }
}

And inside the manager class:

void startAndWait(int numThreads) {
    List<MyRunnable> threads = new ArrayList<MyRunnable>();

    for (int i=0; i<numThreads; i++)
        new Thread(new MyRunnable(threads)).start();

    lock (threads) {
        while (threads.size() > 0)
            wait();
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.