In order to complete a specific task, a set of instructions written in a certain language, that is, a piece of static code
process
An execution of a program, or a program that is running
has its own birth, existence and death process
thread
Processes can be further refined into threads
If a process executes multiple threads at the same time, it supports multithreading
Threads are the unit of scheduling and execution, each thread has an independent running stack and program counter (PC)
A process shares the same memory unit/memory address space => they allocate objects from the same heap, can access the same variables and objects
Communication between threads is simple and efficient, but system resources shared by multiple threads may pose security risks
Parallel and concurrent
Parallelism: Multiple CPUs perform multiple tasks
Concurrency: One CPU executes multiple tasks at the same time
Thread
start() starts the current thread and calls run() in the current thread
run() usually needs to override this method in the Thread class, and declare the operations to be performed by the created thread in this method
currentThread() static method, returns the thread of the current code
getName() gets the name of the current thread
setName() sets the name of the current thread
yield() releases the execution right of the current CPU
join() calls join() of thread b in thread a. At this time, thread a enters the blocking state. Thread a does not end the blocking state until thread b is completely executed.
sleep() makes the current thread sleep for a period of time
isAlice() to see if the thread has ended
publicclassThreadMethods{
publicstaticvoidmain(String[] args){
ThreadMethod1 t1=newThreadMethod1();
t1.setName("线程一");
t1.start();// 主线程命名Thread.currentThread().setName("主线程");for(int i =0; i <100; i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);}if(i==20){
try{
t1.join();}catch(InterruptedException e){
thrownewRuntimeException(e);}}}System.out.println(t1.isAlive());}}classThreadMethod1extendsThread{
@Overridepublicvoidrun(){
for(int i =0; i <100; i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);}try{
Thread.sleep(1000);}catch(InterruptedException e){
thrownewRuntimeException(e);}}}}
Multi-threaded creation
Inherited from the Thread class
Create a subclass that inherits from Thread
Override the run() method of the Thread class
Create an object of a subclass of the Thread class
Call start() on this object
The run() method cannot be called directly
It is not possible to let the thread that has already started() execute again
classMyThreadextendsThread{
@Overridepublicvoidrun(){
for(int i =0; i <100; i++){
if(i%2==0){
System.out.println(i);}}}}publicclassThreadTest{
publicstaticvoidmain(String[] args){
MyThread t1 =newMyThread();
t1.start();for(int i =0; i <100; i++){
if(i%2==0){
System.out.println(i+"****main****");}}}}
Implement the Runnable interface
Create a class that implements the Runnable interface
Implement the class to implement the abstract method run() in Runnable
Create an object of the implementation class
Pass this object as a parameter to the constructor of the Thread class to create an object of the Thread class
Call start() through the Thread class
publicclassThreadRunnable{
publicstaticvoidmain(String[] args){
Runnable1 r1=newRunnable1();Thread t1=newThread(r1);
t1.setName("线程1");
t1.start();Thread t2=newThread(r1);
t2.setName("线程2");
t2.start();}}classRunnable1implementsRunnable{
@Overridepublicvoidrun(){
for(int i =0; i <100; i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);}}}}
Advantages of the Runnable interface
The implementation does not have the limitations of single inheritance of classes
The implementation is more suitable for dealing with the situation where multiple threads share data
Callable interface
Implementation class that implements Callable
Implement the call() method, and declare the method that this thread needs to execute in call()
Create an object of the Callable interface implementation class
Pass the object of the Callable interface implementation class as a parameter to the FutureTask object
Pass the FutureTask object as a parameter to Thread, and call the start() method to start the thread
Get Callable return value
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;publicclassCallableTest{
publicstaticvoidmain(String[] args){
Test t1=newTest();
FutureTask futureTask =newFutureTask(t1);newThread(futureTask).start();try{
Object o1=futureTask.get();
System.out.println(o1);}catch(InterruptedException e){
thrownewRuntimeException(e);}catch(ExecutionException e){
thrownewRuntimeException(e);}}}classTestimplementsCallable{
@Override
public Object call() throws Exception {
int sum=0;for(int i =0; i <100; i++){
if(i%2==0){
System.out.println(i);
sum+=i;}}return sum;}}
Advantages over the Runnable interface
Can have a return value in the run() method
can throw an exception
Support for generic return values
You need to borrow the FutureTask class, such as getting the returned result
Thread Pool
Create multiple threads in advance, put them into the thread pool, obtain them directly when using them, and put them back into the pool after use
It can avoid repeated creation and destruction and realize reuse
Provide a specified number of thread pools
To execute the specified thread operation, you need to provide an object that implements the Runnable or Callable interface implementation class
Close the thread pool
importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassThreadPoll{
publicstaticvoidmain(String[] args){
ExecutorService service =Executors.newFixedThreadPool(10);NumThread1 n1=newNumThread1();NumThread2 n2=newNumThread2();
service.execute(n1);// 适合Runnable
service.execute(n2);// service.submit(); // 适合Callable// 关闭
service.shutdown();}}classNumThread1implementsRunnable{
@Overridepublicvoidrun(){
for(int i =0; i <100; i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+"名字为"+i);}}}}classNumThread2implementsRunnable{
@Overridepublicvoidrun(){
for(int i =0; i <100; i++){
if(i%2!=0){
System.out.println(Thread.currentThread().getName()+"名字为"+i);}}}}
thread priority
priority
MAX_PRIORITY:10
NORM_PRIORITY:5
MIN_PRIORITY:1
set up
getPriority() gets thread priority
setPriority(int p) sets thread priority
After setting the priority, it is not completely safe to prioritize. It can only be said that a thread with a higher priority has a higher probability of execution than a thread with a lower priority.
thread life cycle
New: When an object of the Thread class or its subclasses is declared and created, the new thread object is in the new state
Ready: After being started () in the new state, it will enter the thread queue and wait for the CPU time slice. At this time, it already has the conditions to run, but it has not been allocated CPU resources.
Running: When a ready thread is scheduled and obtains CPU resources, it enters the running state. run() defines the operation and function of the thread
Blocking: In a special case, when it is artificially suspended or performs input and output operations, it will give up the CPU and temporarily terminate its own execution, entering the blocked state
sleep(long time)sleep
join()
wait for synchronization lock
wait()
suspend()
Death: The thread has completed all its work or the thread is forcibly terminated early or terminated due to an exception
Execute run()
Call the thread's stop()
Error/Exception occurs and is not processed
thread safety issues
Synchronized code block
The code that operates on shared data is the code that needs to be synchronized
Shared data: Variables that multiple threads operate on together
If the code for manipulating shared data is completely declared in a method, we might as well make the method declaration synchronous
For non-static synchronization methods, the synchronization monitor is: this; for static synchronization methods, the synchronization monitor is the current class itself
The java.util.concurrent.locks.Lock interface is a tool for controlling access to shared resources by multiple threads
The lock provides exclusive access to shared resources. Only one thread can lock the LOCK object at a time. The thread should obtain the LOCK object before accessing the shared resource.
LOCK, which has the same concurrency and memory semantics as synchronized, is more commonly used in implementing thread safety control, and can display locking and releasing locks
Different threads occupy the synchronization resources needed by the other party and do not give up. They are all waiting for the other party to give up the synchronization resources they need, which forms a deadlock.
No exception will be thrown after deadlock, and the threads of the program are all blocked and cannot continue