Brief introduction
In the contacting 多线程
before in our program can only perform one step at any time, call 单线程
. All procedures are performed sequentially in the path of the single-threaded program developed in front of you must perform, the latter will be performed. The advantages of single-threaded also evident, more stable relative to the multi-threaded, the more scalable, application development is relatively easy. However, because each will have to wait a mandate to start a new task is completed, resulting in lower efficiency than the multi-threaded, and even sometimes the application will appear the phenomenon of suspended animation. The use of multi-threading in favor of fully functional multi-processor. By creating multithreaded process, each thread running on a processor, enabling concurrent applications, so that each processor are fully operational. Multithreading is a very important aspect of learning Java, Java is that each programmer must master basic skills. This article is about some basic knowledge of Java multi-threaded summarized.
The difference between processes and threads
process
Process is the 操作系统资源分配
basic unit, it is the underlying operating system, is the activity that occurs when a program and data execution order on the processor. A program into the memory to run, that becomes a process. Process is in the process of running the program, and with a certain separate functions. In essence, the process of program execution in the operating system of a process that is dynamically generated, dynamic destruction, has its own life cycle and a variety of different operating states. Meanwhile, the process also has concurrency, it can be executed concurrently together with other processes, according to the independent, unpredictable speed forward ( PS:并发性和并行性是不同的概念,并行指的是同一时刻,两个及两个以上的指令在多个处理器上同时执行。而并发指的是同一时刻只有一条指令执行,但是多个进程可以被 CPU 快速交换执行,给我们感觉好像是多个执行在同时执行一样
).
Thread
A thread is 任务调度和执行
a basic unit, also referred to as 轻量级进程
thread by the thread ID, the current instruction pointer (PC), register set and stack components. Thread does not own the system resources, it will only have a little essential resources at run time, but it can share all the resources owned by the process and thread belong to the same process. A thread can only belong to one process, and a process can have multiple threads, but there is at least one thread.
The difference between the two
- Scheduling thread scheduling and assignment as the basic unit processes as the basic unit of own resources
- Concurrency between processes not only can execute concurrently, it can be executed concurrently across multiple threads of the same process
- Have the resources process is an independent unit with the resources, the thread does not have the system resources, but is part of the process of access to resources
- Overhead when creating or revocation process, because the system must be recomputed and resource recovery, leading to system overhead is significantly greater than the cost of creating or revoke thread
Create a thread way
In the Java Thread class represents a thread, all the thread object must be an instance of the Thread class or a subclass of, Java threads are created mainly in the following three ways:
A way to inherit the Thread class
step 1 define a class that inherits from Thread
class, and then override the class run
method, this method represents a thread to complete the task
step 2 to create a thread object is created Thread
instance of a subclass of class
step 3 is created out of two steps object call start
method to start a thread
/**
* @author mghio
* @date: 2019-12-07
* @version: 1.0
* @description: 通过继承 Thread 类的方式创建线程
* @since JDK 1.8
*/
public class CreateThreadByExtendsThread extends Thread {
@Override
public void run() {
IntStream.rangeClosed(1, 10).forEach(i -> System.out.println(Thread.currentThread().getName() + " " + i));
}
public static void main(String[] args) {
CreateThreadByExtendsThread threadOne = new CreateThreadByExtendsThread();
CreateThreadByExtendsThread threadTwo = new CreateThreadByExtendsThread();
CreateThreadByExtendsThread threadThree = new CreateThreadByExtendsThread();
threadOne.start();
threadTwo.start();
threadThree.start();
}
}
复制代码
Second way to achieve Runnable interface
step 1 define a class that implements the Runnable
interface, and then implement the interface run
method, this method also means the thread to complete the task
step 2 to create Runnable
instances of the class interface, and use that as an example of Thraed
constructor parameter to create Thread
an object class, the object is the real thread object
step 3 calling thread object start
method to start the thread
/**
* @author mghio
* @date: 2019-12-07
* @version: 1.0
* @description: 通过实现 Runnable 接口的方式创建线程
* @since JDK 1.8
*/
public class CreateThreadByImplementsRunnable implements Runnable {
@Override
public void run() {
IntStream.rangeClosed(1, 10).forEach(i -> System.out.println(Thread.currentThread().getName() + " " + i));
}
public static void main(String[] args) {
CreateThreadByImplementsRunnable target = new CreateThreadByImplementsRunnable();
new Thread(target, "thread-one").start();
new Thread(target, "thread-two").start();
new Thread(target, "thread-three").start();
}
}
复制代码
Three ways to achieve Callable Interface
step 1 define a class that implements the Callable
interface, and then implement the interface call
method, this method also indicates the thread to complete the task, and returns a value
step 2 Create Callable
instance of the class interface, using the FutureTask
class to wrap Callable
the object, the FutureTask
object encapsulates the Callable
object's call
return value of the method
step 3 and use the FutureTask
object as a Thraed
creation argument constructor of Thread
the object, and call the object's start
method to start a thread
step 4 call the FutureTask
object's get
method to get the return value after the end of the thread execution
/**
* @author mghio
* @date: 2019-12-07
* @version: 1.0
* @description: 通过实现 Callable 接口的方式创建线程
* @since JDK 1.8
*/
public class CreateThreadByImplementsCallable implements Callable<Integer> {
@Override
public Integer call() {
AtomicInteger count = new AtomicInteger();
IntStream.rangeClosed(0, 10).forEach(i -> {
System.out.println(Thread.currentThread().getName() + " " + i);
count.getAndIncrement();
});
return count.get();
}
public static void main(String[] args) {
CreateThreadByImplementsCallable target = new CreateThreadByImplementsCallable();
FutureTask<Integer> futureTask = new FutureTask<>(target);
IntStream.rangeClosed(0, 10).forEach(i -> {
System.out.println(Thread.currentThread().getName() + " 的循环变量 i 的值" + i);
if (i == 8) {
new Thread(futureTask, "有返回值的线程").start();
}
});
try {
System.out.println("有返回值线程的返回值:" + futureTask.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
复制代码
Through the above it can be seen, in fact, by implementing Runnable
the interface and implementation Callable
to create the interface of these two threads basically the same way, the use of realization Runnable
and Callable
when mode interface to create a thread, the thread class only implements the interface can also inherit other classes ( PS:Java 单继承决定
). In this way, multiple threads can share the same target
object, so is ideal for multiple threads to handle the same situation with a resource. Another point is that, using inheritance Thread
when you create multiple threads and the like, simple to prepare, if you need access to the current thread, you do not need to use Thread.currentThread()
the method, used directly this
to obtain the current thread. If the use of these three ways to create a thread, if you create a closed frequently consumed in the actual project affect the performance of the system resources, and you can not use the thread pool thread when the thread back into the pool, then take a time from the thread pool, so our project development mainly use the thread pool, the thread pool can take a look at these two Java thread pool (a) , Java thread pool (II) .
Several state of the thread
A thread is a dynamic process of execution, it also has a process to produce death, in Java, a thread complete life cycle includes a total of five states from the following: New state (New) When using new
keywords and Thread
class or sub-class created after a thread object, the thread entered 新建状态
, then it and other Java objects, just by the JVM allocates memory and initializes variable values of its members, it will remain in this state until a call to the object's start
method.
Ready state (Runnable) When the thread object called start
after the method, the thread into the ready state. Ready thread will be placed in a ready queue, waiting for the JVM scheduler for scheduling. Thread a state of readiness at any time may be executed by the CPU scheduling.
Running state (Running) If the ready state execution is executed by the CPU scheduling, you can perform run
the method, then thread in the thread state. Thread running the most complex, it can become 阻塞状态
, 就绪状态
and 死亡状态
. Note that thread becomes 运行状态
the state before only 就绪状态
.
Blocked (Blocked) thread becomes blocked because of some reason to abandon the use of the CPU, and temporarily stop operating, if performed sleep
, suspend
and other methods, after the release of resources occupied, the thread from 运行状态
entering 阻塞状态
. Waiting for the end of the sleep time or resources to get the re-entry device 就绪状态
. Obstruction can be divided into the following three:
- Waiting for blocking in the
运行状态
thread calls thewait
method, the thread will enter等待阻塞状态
- Synchronous blocking when the thread acquire
synchronized
synchronization lock because the lock is in use by another thread synchronization fails, the thread will enter同步阻塞
- Other blocked by the calling thread
sleep
orjoin
when issuing the I / O request, the thread will enter the blocking state. When thesleep
timeout,join
waiting thread terminates or expires, or I / O processing is completed, the thread back就绪状态
.
Death state (Dead) a in 运行状态
the finished thread execution run
method, or because other termination condition occurs, the thread will enter into 死亡状态
the thread end of the life cycle. Circulation more threads represented by a variety of states is as follows:
Thread common method
A method according to common thread source can be divided into two categories, one is inherited from Object
class method, as follows:
method | description |
---|---|
public final native void notify() | Wake up a single thread waiting on this object's monitor so that it enters就绪状态 |
public final native void notifyAll() | Wake up all threads waiting on this object's monitor so that it enters就绪状态 |
public final void wait() | · Let the current thread is 等待阻塞状态 , until another thread invokes the object's notify method or notifyAll methods, the current thread wakes up, it will release the lock held |
public final native void wait(long timeout) | · Let the current thread is 等待阻塞状态 , until another thread invokes the object's notify method or notifyAll methods, the current thread wakes up |
public final void wait(long timeout, int nanos) | · Let the current thread is 等待阻塞状态 , until another thread invokes the object's notify methods or notifyAll method or some other thread interrupts the current thread, or a certain amount of time has exceeded the actual current thread wakes up |
Another is the Thread
class definition method, as follows:
method | description |
---|---|
public static native void yield() | Suspend the currently executing thread object, and perform other thread, the yield method does not release the lock |
public static native void sleep(long millis) | Thread to sleep (suspended) currently being executed within the specified number of milliseconds, sleep the method does not release the lock |
public final void join() | When calling other threads in a program execution flow join when the method, the calling thread will be blocked until the join thread of execution has been completed |
public void interrupt() | To interrupt this thread, when this method is called, will immediately interrupt flag is set to thread true |
public static boolean interrupted() | Thread A static method of the class, which returns a boolean indicating whether the current thread has been interrupted, interrupted the method returns the interrupt flag in addition to outside, it also clears the interrupt flag (about to interrupt flag is set false ) |
public boolean isInterrupted() | Thread A class instance method that returns a boolean indicating whether the current thread has been interrupted, isInterrupted the method simply returns the interrupt flag will not be clearly labeled terminal |
Thread priority
Each Java thread has a priority, which helps determine the operating system thread scheduling order. Java thread priority is an integer whose value ranges 1(Thread.MIN_PRIORITY )~ 10(Thread.MAX_PRIORITY )
. By default, each thread is assigned a priority NORM_PRIORITY(5)
. Has a higher priority thread is more important to the program, and should allocate processor resources prior to lower priority thread, Thread
class provides setPriority
and getPriority
methods to change and get thread priority ( Note that: thread priority is not guaranteed thread the order of execution, but also very dependent on the platform ).
Reference article