Is lesson me hum seekhenge:
- Thread kya hota hai
- Thread class kya hai
- Thread kaise create karte hain
- run() vs start()
- Important methods
Thread ka matlab:
program ka ek independent execution unit
Example:
ek app me music + download + UI ek saath chalna
multiple threads ka parallel execution
Java me Thread class:
java.lang.Thread
Is class ko extend karke thread create karte hain.
class MyThread extends Thread {
public void run(){
System.out.println("Thread running...");
}
public static void main(String[] args){
MyThread t1 = new MyThread();
t1.start(); // thread start
}
}| Method | Use |
|---|---|
| run() | normal method call |
| start() | new thread create karta hai |
❌ Wrong:
t1.run();✔ Correct:
t1.start();class MyThread extends Thread {
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}| Method | Use |
|---|---|
| start() | thread start |
| run() | logic define |
| sleep() | pause |
| join() | wait |
| setPriority() | priority set |
| getName() | thread name |
try {
Thread.sleep(1000); // 1 second
} catch(Exception e){}t1.setName("Worker Thread");
System.out.println(t1.getName());New → Runnable → Running → Waiting → Terminated
class MyThread extends Thread {
public void run(){
for(int i = 1; i <= 3; i++){
System.out.println(i);
}
}
public static void main(String[] args){
MyThread t = new MyThread();
t.start();
}
}✔ Thread class extend karke thread banate hain
✔ run() me logic likhte hain
✔ start() se new thread create hota hai
- Thread kya hota hai?
- run() aur start() me difference?
- Thread ka lifecycle kya hai?
- sleep() aur join() me difference?
Is lesson me humne seekha:
✔ Thread concept
✔ Thread class
✔ run() vs start()
✔ important methods
✔ lifecycle
Thread class Java me basic multithreading implementation provide karta hai.