java.util.concurrent

Inhalt


Thread (Task) Erzeugung

Der Erzeugung, dem Starten und Stoppen von Threads

Thread[] t = new Thread[anzahl];
for (int i = 0; i < anzahl; i++) {
    t[i] = new RunnableImpl(...,i);
    t[i].start();
}
for (int i = 0; i < anzahl; i++) {
    try { 
        t[i].join(); 
    } catch (InterruptedException e) { 
    }
}

entspricht der folgende Code

ExecutorService 
      pool = Executors.newFixedThreadPool(numCores);
Future[] f = new Future[anzahl];
for (int i = 0; i < anzahl; i++) {
    f[i] = pool.submit( new RunnableImpl(...,i) );
}
for (int i = 0; i < anzahl; i++) {
    try { 
        f[i].get(); 
    } catch (InterruptedException ignored) { 
    } catch (ExecutionException ignored) { 
    }
}
pool.shutdown();

Kritische Bereiche

Zur Behandlung von kritischen Bereichen gibt es zwei Unterpackete java.util.concurrent.locks und java.util.concurrent.atomic.

Zum Beispiel entspricht dem synchronized Konstrukt

synchronized (mutex) { ... statements ... }

die folgende Lock Konstruktion

Lock mutex  = new ReentrantLock();

mutex.lock();
try {
    ... statements ... 
} finally {
    mutex.unlock();
}

Bedingungen

Neben den schon genannten Locks gibt es eine ganze Reihe weiterer nützlicher Klassen, wie Semaphore, Barrieren und Latches.

Mit synchronized und wait():

synchronized (mutex) { 
    ... 
    while ( ? ) {
          mutex.wait();
    }
    ... 
}

synchronized (mutex) { 
    ... 
    if ( ? ) {
       mutex.notify();
    }
    ... 
}

Mit Lock und Condition:

Lock      mutex  = new ReentrantLock();
Condition   cond = mutex.newCondition();

mutex.lock();
try {
    ... 
    while ( ? ) {
          cond.await();
    }
    ...
} finally {
    mutex.unlock();
}


mutex.lock();
try {
    ... 
    if ( ? ) {
       cond.signal();
    }
    ...
} finally {
    mutex.unlock();
}

Erweiterungen im Collection Framework

Eine Reihe von Interfaces und Klassen erweitern die Collection-Tools um nützliche multithreading-Funktionalitäten, wie Queue, BlockingQueue, ConcurrentMap, ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, Exchanger, CopyOnWriteArrayList, CopyOnWriteArraySet, ConcurrentLinkedQueue, ConcurrentHashMap.


Ausblick: Android ActiveTask

Siehe ActiveTask.


© Universität Mannheim, Rechenzentrum, 2005-2016.

Heinz Kredel

Last modified: Fri May 08 00:53:19 CET 2016