JAVA multithreading (1)-----understanding multithreading

1. Know multithreading

Processes and threads

  • Threads are divided on the basis of processes. A process is a dynamic execution process of a program. It has gone through a complete process from code loading, execution to execution completion. This process is also the process of the process itself from generation to development to its final demise.
  • Multithreading is an effective means to realize the concurrency mechanism. Processes, like threads, are a basic unit of concurrency.

image

Java's multithreaded implementation

  • Inherit the Thread class
  • Implement the Runnable interface
  1. Thread class

The Thread class is defined in the java.lang package. As long as a class inherits the Thread class, this class is called a multithreaded operation class. In the Thra subclass, you must explicitly override the Run() method in the Thread class, which is the main body of the thread.

Multi-threaded definition syntax

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-SNguYkBc-1610103102719)(https://uploader.shimo.im/f/xBNe7j0JnuGueHI5.png!thumbnail?fileGuid =VT8YkHRTjJdQt9dG)]

Case:

class XC extends Thread{
    private String name;
    public XC(String name){
        this.name=name;
    }
    public void run(){
for(int i=0;i<10;i++){
    System.out.println(name+"运行"+(++i));}}}

Let's test the thread

public static void main(String[] args) {
    XC xc1=new XC("线程A");
    XC xc2=new XC("线程B");
    xc1.run();
    xc2.run();}

operation result:
image

The result of the operation is executed in order, and not alternately executed, just because the above program is still called in the ordinary method, by calling the method of the object, but if you want to start a thread, you must use the Start method in the Thread class to start multithreading .

Run result after using start method

public static void main(String[] args) {
    XC xc1=new XC("线程A");
    XC xc2=new XC("线程B");
    xc1.start();
    xc2.start();}

image

You can see that the two threads are executing concurrently. The thread that grabs the cpu time slice first executes the thread first. Here we look at the implementation of start.

image

Here, the Start method calls the run() method. Why can't we call the run() method directly?

 public synchronized void start() {
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
        stop0(throwableFromStop);}}
private native void start();

The start() method may throw an exception.
stopBeforeStart is a boolean variable.

The native keyword represents a keyword used by Java to call the native operating system function. Running a Java program in Java calls the native operating system function to complete a specific function.

If you need to implement multithreading, you must need the support of the operating system, because the multi-line operation involves a situation of preempting the CPU, and you have to wait for the CPU to schedule, then this must require the underlying support of the operating system, so you need to use native calls System functions of the machine.

  1. Implement the Runnable interface

In Java, you can also implement multithreading by implementing the Runnable interface. Only one abstract method is defined in the Runable interface.

Multithreading through the Runable interface

image

Examples:

class RunDemo implements Runnable{
    private String name;
    public RunDemo(String name){
        this.name=name;
    }
    public void run(){
        for(int i=0;i<3;i++){
            System.out.println(name+"运行"+i);}}}

Implementation class:

public static void main(String[] args) {
    RunDemo xc2=new RunDemo("线程A");
    RunDemo xc3=new RunDemo("线程B");
    Thread t1=new Thread(xc2);
    Thread t2=new Thread(xc3);
    t1.start();
    t2.start();}

operation result:
image

It can be found from the running effect that the multithreading function has been completed.

Thread and Runnable interface

The connection between the two

public class Thread
extends Object
implements Runnable

It can be seen that thread implements the Runnable interface, you can know that Thread is a subclass of Runable.
The difference between the two

Using the Thread class can not achieve the purpose of resource sharing when operating multiple threads, and the realization of the Runnable interface can achieve resource sharing.

Here we take the example of selling 5 tickets at three windows for comparison.

  • Inherit the Thread class to implement
class T extends Thread{
    private int ticketN=3;
    private String name;
    public T(String name){
        this.name=name;
    }
    public void run(){
        for(int i=0;i<10;i++) {
            if (this.ticketN > 0) {
                System.out.println(name + "卖票:ticket=" + ticketN--); }}}}
public class Ticket {
    public static void main(String[] args) {
        T t1=new T("窗口A");
        T t2=new T("窗口B");
        T t3=new T("窗口C");
        t1.run();
        t2.run();
        t3.run();
    }
}

operation result:
image

Here you can find that each thread has independent resources, and each thread has 3 tickets for sale, indicating that resources are not shared.

  • Ways to implement Runnable
class R implements Runnable{
    private int ticketN=3;
    public void run(){
        for(int i=0;i<10;i++) {
            if (this.ticketN > 0) {
                System.out.println( "卖票:ticket=" + ticketN--); }}}}

Run class:

public static void main(String[] args) {
    R r1 = new R();
    Thread t1=new Thread(r1);
    Thread t2=new Thread(r1);
    Thread t3=new Thread(r1);
    t1.run();
    t2.run();
    t3.run();}

operation result:
image

It can be found that although three threads were created, a total of 5 tickets were sold for the three threads.

Conclusion of the use of Thread and Runnable interfaces

Runnable advantages

  • Suitable for multiple same program codes next time you go to deal with the same resource.
  • It can avoid the impact caused by the limitation of single inheritance.
  • Enhance the robustness of the program, the code can be shared by multiple threads, the code and data are independent

The integrated runnable interface is better.

Thread status

  • Create state, prepare to return a multi-threaded instance, Thread t=newThread();
  • Ready state, call the start method
  • Running status: call the run() method
  • Blocked state, temporarily suspend execution, and may give resources to other threads for use.

image

Guess you like

Origin blog.csdn.net/qq_44762290/article/details/112379256