Matura: Softwareentwicklung & Informationssysteme

3.3. Threads und Synchronisierung

Synchronized

synchronized void showMsg(String  msg){ //synchronized method  
    for (int i=1; i<=5; i++) {  
        System.out.println(msg);  
        try {  
            Thread.sleep(500);  
        } catch (Exception e) {
            System.out.println(e);
        }  
    }  
}  

https://www.delftstack.com/howto/java/monitor-in-java/

Locks

Lock lock = ...; 
lock.lock();
try {
    // access to the shared resource
} finally {
    lock.unlock();
}

ReentrantLock

public class SharedObject {
    //...
    ReentrantLock lock = new ReentrantLock();
    int counter = 0;

    public void perform() {
        lock.lock();
        try {
            // Critical section here
            count++;
        } finally {
            lock.unlock();
        }
    }
    //...

Synchronized Collections

Collection<Integer> syncCollection = Collections.synchronizedCollection(new ArrayList<>());

ConcurrentCollections

Unterschied Concurrent/Synchornized Collections

Semaphoren