Home  >  Article  >  Java  >  What does java multithreading refer to?

What does java multithreading refer to?

coldplay.xixi
coldplay.xixiOriginal
2020-08-11 13:18:223974browse

Java multi-threading refers to: Multi-threading is a mechanism that allows multiple instruction streams to be executed concurrently in a program. Each instruction stream is called a thread and is independent of each other. All variables in Java are Stored in main memory and shared by all threads.

What does java multithreading refer to?

Detailed explanation of java multi-threading:

1. Understanding multi-threading

Multithreading is a mechanism that allows multiple instruction streams to be executed concurrently in a program. Each instruction stream is called a thread and is independent of each other. Threads are also called lightweight processes. They have independent execution control like processes and are scheduled by the operating system. The difference is that threads do not have independent storage space, but share a storage space with other threads in the process to which they belong. This makes Communication between threads is much simpler than that of processes.

Specific to the Java memory model, since Java is designed as a cross-platform language, it is obvious that there must be a unified model in terms of memory management. The system has a main memory (Main Memory). All variables in Java are stored in the main memory and are shared by all threads. Each thread has its own working memory (Working Memory). What is stored in the working memory is a copy of some variables in the main memory. All thread operations on variables are performed in the working memory. Threads cannot directly access each other. , variable transfer needs to be completed through main memory.

The execution of multiple threads is concurrent, that is, logically "simultaneously", regardless of whether it is physically "simultaneously". If the system has only one CPU, then true "simultaneity" is impossible. The biggest difference in programming between multi-threading and traditional single-threading is that since the control flows of each thread are independent of each other, the code between each thread is executed out of order, which will cause thread scheduling, synchronization and other problems. Network management network bitsCN.com

Relevant learning recommendations: java basic tutorial

2. Implementing multi-threading in Java

We might as well imagine what we need to do in order to create a new thread? Obviously, we must specify the code to be executed by this thread, and this is all we need to do to implement multi-threading in Java!

As a completely object-oriented language, Java provides the class java.lang.Thread to facilitate multi-threaded programming. This class provides a large number of methods to facilitate us to control our own threads.

So how do we provide Java with the code we want the thread to execute? Let's take a look at the Thread class. The most important method of the Thread class is run(), which is called by the method start() of the Thread class and provides the code to be executed by our thread. In order to specify our own code, just override it!

Method 1: Inherit the Thread class and rewrite the method run(). We rewrite run() in the subclass of the created Thread class and add the code to be executed by the thread. The following is an example:

public class TwoThread extends Thread {
    public void run() {
        for ( int i = 0; i < 10; i++ ) {
            System.out.println("New thread");
        }
    }
    public static void main(String[] args) {
        TwoThread tt = new TwoThread();
        tt.start();
        for ( int i = 0; i < 10; i++ ) {
            System.out.println("Main thread");
        }
    }
}

This method is simple and clear, and is in line with everyone's habits. However, it also has a big disadvantage, that is, if our class has inherited from a class, it cannot inherit Thread. kind.

Method 2: Implement the Runnable interface

The Runnable interface has only one method run(). We declare that our class implements the Runnable interface and provides this method, and writes our thread code into it. This part of the task is completed. However, the Runnable interface does not have any support for threads. We must also create an instance of the Thread class, which is achieved through the constructor public Thread (Runnable target); of the Thread class. The following is an example:

public class MyThread implements Runnable {
int count=1, number;
public MyThread(int num) {
number = num;
System.out.println("创建线程 " + number);
}
public void run() {
while(true) {
System.out.println("线程 " + number + ":计数 " + count);
if(++count== 6) return;
}
}
public static void main(String args[]) {
for(int i = 0; i < 5; i++)
new Thread(new MyThread(i+1)).start();
}
}

Using the Runnable interface to implement multi-threading allows us to contain all code in one class, which is conducive to encapsulation. Let us study some issues in the use of multi-threading.

3. Four states of threads

1. New state: The thread has been created but has not yet been executed (start() has not been called yet).

2. Executable state: The thread can be executed, although it is not necessarily executing. CPU time may be allocated to this thread at any time, causing it to execute.

3. Blocked state: The thread will not be allocated CPU time and cannot be executed; it may be blocked in I/O or blocked in a synchronization lock.

4. Death state: Under normal circumstances, the return of run() will cause the thread to die. Calling stop() or destroy() also has the same effect, but it is not recommended. The former will generate an exception, and the latter is a forced termination and will not release the lock.

4. Thread priority

    线程的优先级代表该线程的重要程度,当有多个线程同时处于可执行状态并等待获得 CPU 时间时,线程调度系统根据各个线程的优先级来决定给谁分配 CPU 时间,优先级高的线程有更大的机会获得 CPU 时间,优先级低的线程也不是没有机会,只是机会要小一些罢了。

    你可以调用 Thread 类的方法 getPriority() 和 setPriority()来存取线程的优先级,线程的优先级界于1(MIN_PRIORITY)和10(MAX_PRIORITY)之间,缺省是5(NORM_PRIORITY)。

五、线程的同步

    由于同一进程的多个线程共享同一片存储空间,在带来方便的同时,也带来了访问冲突这个严重的问题。Java语言提供了专门机制以解决这种冲突,有效避免了同一个数据对象被多个线程同时访问。

    我们只需针对方法提出一套机制,这套机制就是 synchronized 关键字,它包括两种用法:synchronized 方法和 synchronized 块。

    1. synchronized 方法:通过在方法声明中加入synchronized关键字来声明 synchronized 方法。synchronized 方法控制对类成员变量的访问:每个类实例对应一把锁,每个 synchronized 方法都必须获得调用该方法的类实例的锁方能执行,否则所属线程阻塞,方法一旦执行,就独占该锁,直到从该方法返回时才将锁释放,此后被阻塞的线程方能获得该锁,重新进入可执行状态。这种机制确保了同一时刻对于每一个类实例,其所有声明为 synchronized 的成员函数中至多只有一个处于可执行状态(因为至多只有一个能够获得该类实例对应的锁),从而有效避免了类成员变量的访问冲突(只要所有可能访问类成员变量的方法均被声明为 synchronized)。

    在 Java 中,不光是类实例,每一个类也对应一把锁,这样我们也可将类的静态成员函数声明为 synchronized,以控制其对类的静态成员变量的访问。

    synchronized 方法的缺陷:若将一个大的方法声明为synchronized 将会大大影响效率,典型地,若将线程类的方法run()声明为synchronized ,由于在线程的整个生命期内它一直在运行,因此将导致它对本类任何synchronized方法的调用都永远不会成功。

    2. synchronized 块:通过 synchronized关键字来声明synchronized 块。语法如下:

synchronized(syncObject) {
//允许访问控制的代码
}

    synchronized 块是这样一个代码块,其中的代码必须获得对象 syncObject 的锁方能执行,具体机制同前所述。由于可以针对任意代码块,且可任意指定上锁的对象,故灵活性较高。

相关学习推荐:编程视频

The above is the detailed content of What does java multithreading refer to?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn