Why Thread
- Single-threaded application:
- leads to poor response
- has poor prefomance
- has poor utilization of CPU resources
Thread in Java
- A/multiple thread is one/multiple task of an/- execution flow, flowing from beginning to end
- Organzied programs into logically seperate paths
- Can preform independent
- Share access to common resources.
- Language and api provide concurrency in JAVA
- Multiple thread if execution
- Each thread has its own method-call stack
- 程序计数器
Life cycle of a thread
- New
在调取start()之前, 创建 thread class 的实例 - Runnable
调取start()之后 - Running
scheduler被选中 - Non-Runnable(Blocked)
thread alive,but currently not eligible to run - Terminated
run()还在的时候死掉了
Syntax:
- extend Thread Class
public class ClassName extends Thread{
public void run(){
}
}
- runnable obj
public class ClassName implements Runnable{
public void run(){
}
}
Thread Schedular
- JVM
- Decides which thread should run
- Random select
- Preemptive: priority
- Time slicing scheduling:predifine->reenter
Intrinsic lock
- Protect multi-thread task
- Fac to every obj
- Dadada
好处
- prevent thread interference
- Prevent consistency problem
同步种类
- By process
- By Thread
- (inter-thread communication)
- Mutual exclusive
Synchronized void method(…){
}
Synchronized(this){
}
Sleep()
- Purpose: use to sleep a thread for a setting time.
- Implimentation:
@ Override
public void run(){
try{
Thread.sleep(1000);
}catch(InterruptedException e{
System.out.println(e);
}
}
join()
- Purpose: use to forced one thread to wait for antoher thread to finish.
- Implimentation:
thread1.start()
try{
thread1.join();
}catch(InterruptedException e{
System.out.println(e);
}
thread2.start();
interrupt()
- use to “terminated” the status of a task
- 常用表达 Thread.CurrentThread().isInterrupted()