Introduction

Terms #

Parallelism has the goal that the program is finished faster. For example, a sequence can be divided into several subsequences, so that the parts can then run on different processes.

Concurrency does not necessarily aim at a faster program, but at being able to execute processes in an interlocked way. For example, processes can have read access to shared resources at the same time or be locked when one needs to write.

However, it is true that there are always multiple threads interacting.

Topics #

Java offers the programmers some possibilities to optimize the program with several threads. Central is certainly the monitor synchronization as well as the specific synchronization primitives. For the parallelism then also the Thread Pools are important. If you want to work lock-free, the memory model with the “volatile” keyword and the atomic classes must be well known by the programmer.

Introduction #

There are two different operating system components that must be distinguished. The former is a process that has its own address space. The latter is the thread that runs within a process and shares the address space with other threads. The latter means that a thread can access variables and generally resources of other threads.

Java is a single process system. This means that the JVM (Java Virtual Machine) is a process in the operating system that can have multiple threads.

A thread must be started after it is instantiated. For example, this can be done like this:

Thread myThread = new Thread() -> {
	//Thread Code.
});

myThread.start();

You can also pass a runnable to the thread constructor or even inherit it from the thread class.

It is important to know that a thread only starts to run with the start() method. Also, unhandled exceptions from other threads are ignored. The thread is finished when the run() method has run.

If multiple threads have been started, it is pretty certain that they will have to wait for termination at some point. This can be done with the join() method. If the thread is to be terminated as soon as the program exits, the thread can be marked as a daemon. These are terminated when the main function returns.

Calendar September 21, 2021