| marp | true |
|---|---|
| theme | default |
| _class | lead |
| author | Ali Ahmad |
| paginate | true |
| backgroundColor | |
| backgroundImage | url('./assets/background.jpg') |
- Lambda's
- Streams
- Threads
- Process
- Using Threads
- Daemon threads
- Thread LifeCycle
-
A thread is a single sequential flow of control within a program.
- Single sequential flow of control
- Allow the program to split into simuntanously running task
- As a metaphor - A worker who is building a wall
- Load program to memory
- Allocate the resources
- Execute the program
-
A process is a manifestation of a run state of an application.
- Binary instructions loaded into memory
- Get access to resources like memory
- Resource is protected from other processes
- A process can be single threaded or multi threaded
- A process can spawn multiple threads
- Unlike process, threads in a process can share the same memory and resources
- A single process (JVM)
- Consists of various threads (Garbage collector, main, etc)
- Application thread - responsible for running the main method
- Identify the piece of code, that you want to run in a separate thread
- Create a Runnable implementation for that task
public class MyRunnable implements Runnable {
@Override
public void run() {
MyTask.run();
}
}Runnable myRunnable = () -> MyTask.run();- Create a thread and pass the runnable to it
- Start the thread
Thread myThread = new Thread(myRunnable);
myThread.start();- Thread class is just there, defining meta data for the thread
- JVM calls the underlying OS threading API
- When the run method returns
- When exception is thrown
-
When you spawn threads, it ends when all the threads end
- Daemon threads are threads that end when the main thread ends
- Do not want a thread to extend beyound the lifecycle of the application, create a daemon thread
- Daemon threads are created by calling
setDaemon(true)on the thread object
Thread myThread = new Thread(myRunnable);
myThread.setDaemon(true);
myThread.start();- New
- Runnable
- Blocked
- Waiting
- Timed Waiting
- Terminated
- Running vs Runnable?