Thread Basics
- Program contains multiple processes and process consists of a single or multiple threads, thread is also a small lightweight sub-process
- Context switching between threads is less expensive than processes
- Intercommunication between thread is easy than process communication
- There are 2 types of threads - user threads & daemon threads, “main” is first user thread in any java application
- Once thread is started, it’s execution depends on the OS implementation of time slicing, we cannot control/guarantee thread execution
- A thread always inherits properties from parent thread
Thread Creation
- Implement java.lang.Runnable (preferred due to multiple inheritance issue)
- Class will Implement Runnable interface
- Create an object of
class
- Create Thread object and
pass class reference in #2 to Thread
- Call start() method on Thread object
- Calling start() method internally calls run() method of class
- Extend java.lang.Thread
- Class will extend Thread class
- Create an object of class
- Call start() method on the object
- Calling start() method internally calls run() method of class
- NEW: A thread that has not yet started i.e. after creating a thread with new operator
- RUNNABLE: A thread executing in the JVM i.e. after calling start()
- RUNNING: It’s NOT a valid state in Oracle 15 docs
- BLOCKED: A thread that is blocked waiting for a monitor lock is in this state
- WAITING: A thread that is waiting for another thread to perform a particular action
- TIMED_WAITING: A thread that is waiting for specified waiting time
- TERMINATED: A thread that has exited
- Thread()
- Thread(Runnable
target)
- Thread(Runnable
target, String name)
- Thread(String
name)
- Thread(ThreadGroup
group, Runnable target)
- Thread(ThreadGroup
group, Runnable target, String name)
- Thread(ThreadGroup
group, Runnable target, String name, long stackSize)
- Thread(ThreadGroup
group, Runnable target, String name, long stackSize, boolean
inheritThreadLocals)
- Thread(ThreadGroup
group, String name)
Runnable Target: Class implementing runnable interface or
extending Thread class
Stack Size: approximate number of bytes space that VM should
allocate for the thread, on a few OS, it will not have any effect though
No comments:
Post a Comment