Documente Academic
Documente Profesional
Documente Cultură
Multithreading
1. Thread:
a. worker it will do some job
b. Single unit of a process (task) e.g. Spell Check in Ms Word.
c. In JVM, the main method is invoked by a thread main. GC is also a
thread in JVM (Garbage Collector)
d. Threads are used in client server application.
2. Thread Life Cycle:
a. States: New, Run able(Ready to run)
star
t()
Runnin
g
New
Run able
interrupt() , notify(),
dead
sleep() , wait(),
main
Saurav
Priority: 5
Thread[Saurav,5,main]
Thread[Saurav,10,main]
3. Creating a thread:
a. Two ways
i. extends class with Thread class
ii. by passing a run able object to the thread class constructor.
Runnable<<interface>>
void run();
Runnable<<interface>>
Thread
void run();
MyThread
MyThread
public void
run() {
package com.oracle.threads;
O/P
Main runing
Main Ends
Child Thread running
**Example:
package com.oracle.threads;
}
}
package com.oracle.threads;
O/P:
20 40 or 40 40 or 40 20 because only a single object is present and the data
variable is shared by the two threads.
5. sleep and wait block the thread. but sleep method holds the lock and wait
doesnt.
a. Monitor all codes inside sync block.
6. notify() wakes up the sleeping thread.