多线程基础知识
Concept of Thread
Thread is basically a lightweight sub-process(子进程), a smallest unit ofprocessing. Multiprocessing and multithreading,
both are used to achieve multitasking.But we use multithreading
than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory,
and context-switching between the threads takes less time than process.Java Multithreading is mostly used in games, animation etc.
Advantage of Java Multithreading
1、It doesn't block(阻塞) the user because threads are independent(相互独立的) and you can perform multiple operations at same time.
2、You can perform many operations together so it saves time.
3、Threads are independent so it doesn't affect other threads if exception occur in a single thread.
Multitasking(多任务)
Multitasking is a process of executing multiple tasks simultaneously(同时). We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:
1、Process-based Multitasking(Multiprocessing)
2、Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process have its own address in memory i.e. each process allocates separate memory area.Process is heavyweight.Cost of communication between the process is high.Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.(共享内存)Thread is lightweight.(轻量级)Cost of communication between the thread is low.(线程间通信相对容易)
What is Thread in java ?
A thread is a lightweight sub process, a smallest unit of processing.
It is a separate path of execution.Threads are independent,
if there occurs exception in one thread, it doesn't affect other threads.
It shares a common memory area.Thread is executed inside the process.
There is context-switching between the Thread.There can be multiple processes
inside the OS and one process can have multiple threads.
Note: At a time one thread is executed only(单处理器系统).
Life Cycle of a Thread
A thread can be in one of the five states. According to sun,
there is only 4 states in thread life cycle in java new, runnable,
non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining
it in the 5 states.The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
1、New(新建状态)
2、Runnable(可执行状态)
3、Running(正在执行状态) runnable状态下获得cpu调度
4、Non-Runnable (Blocked阻塞状态)
5、Terminated(结束死亡状态)
Create thread
There are two ways to create a thread:
1、By extending Thread class
2、By implementing Runnable interface.
Thread class
Thread class provide constructors and methods to create and perform operations on
a thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:(构造方法)
Thread() 无参构造方法
Thread(String name) 给名字的构造方法
Thread(Runnable r) 指定Runnable子类对象
Thread(Runnable r,String name) 指定Runnable子类对象和名字
Commonly used methods of Thread class:(最常用的Thread类两个方法)
1、public void run(): is used to perform action for a thread.
2、public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
**Note:只有start()方法才是启动线程,多线程是由操作系统支持的,所以run方法并不能启动多线程.
通过查看Thread源代码发现低层调用的native 本地方法,所以start()才是启动多线程**。
Runnable interface
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().
1、public void run(): is used to perform action for a thread.(该接口只定义了这一个方法)
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
Note:启动Runnable实现类的线程只能借助Thread类的Start方法。
Java中的线程调度
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that decides which thread should run.There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.Only one thread at a time can run in a single process.The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
Difference between preemptive scheduling and time slicing(抢占式和时间分片调度)
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.
Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
1、public static void sleep(long miliseconds)throws InterruptedException
2、public static void sleep(long miliseconds, int nanos)throws InterruptedException
As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.
Can we start a thread twice ?
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
What if we call run() method directly instead start() method?
Each thread starts in a separate call stack.Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
The join() method
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Note:强行抢夺cpu执行权
Priority of a Thread (Thread Priority)
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
3 constants defiend in Thread class:
public static int MIN_PRIORITY(0)
public static int NORM_PRIORITY(5)
public static int MAX_PRIORITY(10)
Note:优先级并不可靠
Daemon Thread in Java
Daemon thread in java is a service provider thread that provides services to theuser thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt.
The jconsole tool provides information about the loaded classes, memory usage,
running threads etc.
Points to remember for Daemon Thread in Java
1、It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
2、Its life depends on user threads.
3、It is a low priority thread.
Why JVM terminates the daemon thread if there is no user thread?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
Note:If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
public void setDaemon(boolean status)
public boolean isDaemon()
Note:守护线程作了解即可
Java Thread Pool
Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.
Advantage of Java Thread Pool Better performance It saves time because there is no need to create new thread.
Real time usage
It is used in Servlet and JSP where container creates a thread pool to process the request.
Note:ExecutorService and Executors
Java Garbage Collection
In java, garbage means unreferenced objects.Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.To do so, we were using free() function in C language and delete() in C++.But, in java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
1、It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
2、It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways such as:
1、By nulling the reference(用null赋值)
2、By assigning a reference to another(改变引用地址)
3、By annonymous object etc.(匿名对象)
备注:本质就是要让对象没有被引用
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:protected void finalize(){}
Note:
The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new,you can use finalize method to perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
Note:Garbage collection is performed by a daemon thread called Garbage Collector(GC).
This thread calls the finalize() method before object is garbage collected.
Note: Neither finalization nor garbage collection is guaranteed.(不论是哪个方法都无法保证一定回收垃圾)
Java Runtime class
Java Runtime class is used to interact with java runtime environment.
Java Runtime class provides methods to execute a process, invoke GC,
get total and free memory etc. There is only one instance of java.lang.Runtime
class is available for one java application.
The Runtime.getRuntime() method returns the singleton instance of Runtime class.
Thread类的核心方法
构造方法
public Thread(){};
public Thread(Runnable target){};
public Thread(String name){};
public Thread(Runnable target, String name){};
普通方法
public synchronized void start(){} 启动线程方法;
public void run(){} 线程真正执行的代码块;
public static native Thread currentThread(); 获得当前线程
public static native void sleep(long millis) throws InterruptedException; 让出cpu调度权,但并不会释放自己拥有的资源比如锁资源
public static native void yield(); 让出cpu调度权停止当前线程,让同等优先权的线程运行。如果没有同等优先权的线程,那么Yield()方法将不会起作用
public final synchronized void join(long millis);强行抢夺cpu调度器
public void interrupt();打断当前线程
//线程唤醒和等待方法
public final native void notify();唤醒一个等待线程
public final native void notifyAll();唤醒该对象监视的所有线程
public final native void wait(long timeout) throws InterruptedException;让该线程等待(释放了锁资源的)
wait()方法和notify()方法是对应的,只有在wait的时候释放了锁资源,notify之后的另一个线程才有意义,如果执行wait的线程不释放锁资源那么就会产生死锁了。
public final void setDaemon(boolean on) ;设置守护线程
note:多线程开发中比较经典的问题就是生产者和消费者模型
1、一个生产者和一个消费者
2、多个生产者和多个消费者