Home >Java >javaTutorial >This is definitely the most detailed explanation of Java multi-threading
In the previous operating system processes and threads, threads have been explained in detail. For multi-threading in java Thread implementation, this article will give some more introduction.
For thread status in Java, we can use a five-state model to represent it, which are:
Five states of creation, ready, running, blocking, and termination
Creation state: JVM calls the main() method to create a main thread. The main thread starts a child thread by calling the start() method of the thread object. The newly created thread is in the creation state. When the thread runs various After the conditions are met, enter the ready queue.
For other various states, please refer to the explanations in processes and threads.
There are two ways to create a thread in Java, namely by inheriting the Thread class and implementing the Runnable interface. The specific introduction is as follows:
Multi-threading can be implemented in Java through the Thread class and its subclasses and the Runnable interface.
The Thread class can directly define thread objects, but generally it is necessary to define a subclass of the Thread class to implement multi-threading to meet the special requirements of programming. Restricted by Java's single inheritance, in practical applications, almost all multi-threaded applications implement multi-threading by implementing the runnable interface.
In other words, if the newly created class wants to inherit other classes, because multiple inheritance is not supported in Java, multi-threaded tasks can only be completed by implementing the java.lang.Runnable interface. Runnable is suitable for multiple identical program codes. Threads are used to process the same resource, effectively separating the virtual CPU (thread) from the code and data of the program.
The codes for the implementation of the two threads are as follows:
public class ThreadDemo extends Thread { int i = 0; public void run(){ while (i<10){ System.out.println("实现Thread类继承的线程,正在占有处理机运行……"+i); try{ sleep(1000); i++; }catch (InterruptedException e){ e.printStackTrace(); } } } }
In the main function, we only need to instantiate the class and call the start() method to create a thread.
public class RunnableDemo implements Runnable { int i = 0; @Override public void run(){ while (i<10) { System.out.println("实现Runnable接口的线程,正在占有处理机运行……" + i); try { Thread.sleep(1000); i++; } catch (InterruptedException e) { e.printStackTrace(); } } } }
Implementation method in main function:
Thread thread = new Thread(RunnableDemo ); Thread.start();
Start of thread: thread.start()
End of thread: Set Set a mark variable to end the corresponding loop and method
Temporarily prevent the execution of the thread: Try{Thread.sleep(1000);}catch(InterruptedException e){ }
Set the thread Priority: setPriority(int priority) method
Max_priority The highest priority a thread can have (usually 10)
Min_priority The highest priority a thread can have (usually 1)
Normal_priority The default priority assigned to the thread (usually 5)
There are two types of threads in Java: User Thread (user thread) and Daemon Thread (daemon thread) ), the role of the Daemon thread is to provide services for the running of other threads, such as garbage collection threads. In a Java program, if there are non-Daemon threads, the entire program will not end.
Set the daemon thread through the setDaemon(true) method
Jvm is responsible for allocating CPU to threads, which is called thread scheduling. Principle : High-priority threads first run multiple threads of the same priority and directly allocate CPU resources according to time slice rotation
Uncertainty of threads: a simple statement in Java Corresponding to multiple instructions in the CPU, when a thread has just executed an instruction and is scheduled, subsequent threads repeatedly call the original data, resulting in thread uncertainty (not atomic)
Thread synchronization: When threads running at the same time need to share data, they must consider the status and behavior of other threads. At this time, synchronization needs to be implemented. Java introduces the concept of object mutex locks to ensure shared data operations. of integrity. Each object corresponds to a monitor (monitor), which has a mark called a "mutex (lock, mutex)". This mark is used to ensure that only one thread can access the object at any time. The keyword synchronized is used to contact the object's mutex lock.
Usage of synchronized:
For code fragments synchronized (object) {}
For a method: synchronized In the method declaration, Public synchronized void push (char c) {} is equivalent to synchronized (this), indicating that the entire method is a synchronized method
Thread synchronization control:
Use the wait() method to Release the object lock
Use notify() or notifyAll() to make one or all waiting threads enter the ready state
In Java, wait and notify can be placed in synchronized, during synchronized execution When a thread calls the wait method of an object, it will release the object lock identifier and then enter the waiting state. Then other threads call the notify() or notify() method to notify the waiting thread.
The specific code is as follows:
class CubbyHole { private int index = 0; private int[] data = new int[3]; public synchronized void put(int value){ while (index == data.length){ try{ this.wait(); }catch (InterruptedException e){ e.printStackTrace(); } } data[index++] = value; this.notify(); } public synchronized int get(){ while (index <=0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int value = data[index--]; this.notify(); return value; } }
In simple synchronization, locking and unlocking can easily cause deadlock problems, that is, waiting for each other. Java introduced some methods after 1.5 to solve multi-threading problems.
Since JDK1.5, a series of more useful classes such as single variables, collections, Timers, and thread pools have been provided.
Atomic variable java.util.concurrent.atomic package AtomicInteger class
GetAndIncrement() method ensures that thread access is safe
Concurrent collection class Java.util.concurrent Add some classes CopyOnWriteArrayList and CopyOnWriteSet to the package
Suitable for objects that are rarely written but frequently read
ConcurrentHashMap
ArrayBlockingQueue producers and consumers use put and get
Use thread pool
Thread pool related class ExecutorService interface, ThreadPoolExecutor class Executors tool class
Common usage ExecutorService pool = Executors.newCachedThreadPool();
Use its execute(Runnable r) method
The above is the detailed content of This is definitely the most detailed explanation of Java multi-threading. For more information, please follow other related articles on the PHP Chinese website!