Java Multithreading Flashcards
What is Multithreading ?
Multithreading is when a program contains two or more parts which can run concurrently even with different tasks.
=> Java is a Multithereaded language.
How to achieve multithreading
you need java.lang.Thread class
Thread Life Cycle
*New: it is known also as born thread , it’s the beginning state of a thread.
*Runnable:once a thread is born thread , we can execute it (in this state thread considered to be executed).
*Waiting: a thread transitions to waiting state, waiting a signal from another executed/runnable thread
*Timed Waiting: after an interval of time expires a thread can execute or also if the thread which wait for is executed.
*Terminated(Dead):is the state where a thread complete its task.
Thread Priorities
Java thread priorities are in the range of MIN_PRIORITY ( a constant of 1 ) and MAX_PRIORITY( a constant of 10 ) by default each thread have NORM_PRIORITY(a constant of 5 )
Even though a max_priorities has more proriety to be executed first by program , it doesn t guarantee execution order of threads and thread priority is a platform dependant.
Create a thread by implementing Runnable interface
*Implement run() method:Here we write our business logic code.
*Instantiate a thread Object:you can instantiate using this Thread constructor :
Thread(Runnable threadObj, String threadName) where threadObj is name of class that implements Runnable or extends Thread(second arg (threadName) is optionnal).
*Call thread using start() method: run thread, we can also override it and do instantiation inside it
Create a thread by extending a Thread Class
Same steps of implementing Runnable interface, the difference is we extend Thread class instead of implementing Runnable interface and it give us more flexibility with Thread class methods.
Some Thread Class methods
start(),run(),setName(),setPriority(),setDaemon(), join(),interrupt(),isAlive(),sleep()
*setDaemon(): A thread becomes a daemon thread
*join():it is invoked on a second thread causing the current thread to block until the second end or time expire
*interrupt():Causing a thread to continue if it was blocked , if not blocked , it is interrupted until other threads execute.
Daemon Thread
A daemon thread is created to support user threads.Once all threads are closed , daemon thread terminates. example Garbage collector.
JVM Shutdown Hook
*Controlled process:happens if System.exit() method is called or with Ctrl+C or if the last non-daemon thread terminates
*Abrupt manner: happens after a kill signal , with Runtime.getRuntime().halt() call or an OS menace.