Java learning summary: 26

Threads and processes

A process is a dynamic execution process of a program. It has gone through a complete process from code loading and execution to completion of execution. This process is also the process of the process itself from generation, development to final demise.
Threads are smaller execution units than processes. Threads are further divided on the basis of processes. A process may contain multiple threads that are executed simultaneously.The difference between process and thread

Note: All threads must be attached to the process to exist. Once the process disappears, the thread will also disappear. Java is one of the few development languages ​​that supports multithreading.

Multi-threaded implementation

In Java, if you want to implement a multi-threaded program, you must rely on the main body of a thread (representing the main class of a thread). But the main class body of this thread also needs some special requirements when it is defined, that is, this class needs to inherit the Thread class or implement the Runnable (Callable) interface to complete the definition.

Inherit Thread class

java.lang.Thread is a class responsible for thread operations, any class only needs to inherit the Thread class to become the main class of a thread. The definition format of the thread main class is as follows:

class 类名称 extends Thread{	//继承Thread类
	属性...;					//类中定义属性
	方法...;					//类中定义方法
	public void run(){			//覆写Thread类中的run()方法,此方法是线程的主体
		线程主体方法;
	}
}

Example: Start multiple threads

package Project.Study.Multithreading;
import java.lang.Thread;

class MyThread extends Thread{		//这就是一个多线程的操作类
    private String name;			//定义类中的属性
    public MyThread(String name){	//定义构造方法
        this.name=name;
    }
    @Override
    public void run(){				//覆写run()方法,作为线程的主操作方法
        for (int x=0;x<200;x++){
            System.out.println(this.name+"-->"+x);
        }
    }
}
public class Test1 {
    public static void main(String[] args){
        MyThread mt1=new MyThread("线程A");	//实例化多线程对象
        MyThread mt2=new MyThread("线程B");
        MyThread mt3=new MyThread("线程C");
        mt1.start();						//启动多线程
        mt2.start();
        mt3.start();
    }
}
//结果
//线程B-->0
//线程C-->0
//线程A-->0
//线程C-->1
//线程B-->1
//线程C-->2
//后面省略...

Note: Calling the run () method directly does not start multithreading. The only method for multithreading is the start () method in the Thread class: public void start () Code)

Implement the Runnable interface

The biggest disadvantage of the Thread class to achieve multi-threading is the problem of single inheritance, so Java can also use the Runnable interface to achieve multi-threading. This interface is defined as follows:

@FunctionalInterface		//函数式接口
public interface Runnable{
    public void run();
}

Example: Using Runnable to achieve multithreading

package Project.Study.Multithreading;

class MyTread2 implements Runnable{	//定义线程主体类
    private String name;			//定义类中的属性
    public MyTread2(String name){	//定义构造方法
        this.name=name;
    }
    @Override
    public void run(){				//覆写run()方法
        for(int x=0;x<200;x++){
            System.out.println(this.name+"-->"+x);
        }
    }
}
public class Test2 {
    public static void main(String []args){
        MyTread2 mt1=new MyTread2("线程A");	//实例化多线程类对象
        MyTread2 mt2=new MyTread2("线程B");
        MyTread2 mt3=new MyTread2("线程C");
        new Thread(mt1).start();			//使用Thread启动多线程
        new Thread(mt2).start();
        new Thread(mt3).start();
    }
}
//结果:
//线程C-->0
//线程A-->0
//线程B-->0
//线程A-->1
//线程C-->1
//线程C-->2
//后面省略...

Example: Use Lambda expression operation

package Project.Study.Multithreading;

public class Test2 {
    public static void main(String []args){
        String name="线程对象";
        new Thread(()->{
            for(int x=0;x<200;x++){
                System.out.println(name+"-->"+x);
            }
        }).start();
    }
}
//结果:
//线程对象-->0
//线程对象-->1
//线程对象-->2
//线程对象-->3
//线程对象-->4
//线程对象-->5
//后面省略...

Using Callable interface to achieve multi-threading

The Callable interface solves the problem that the run () method in the Runnable interface cannot return the operation result.
The definition of this interface is as follows:

@FunctionalInterface
public interface Callable{
    public V call() throws Exception;
}

Define a thread body class

import java.util.concurrent.Callable;
class MyThread3 implements Callable<String>{	//多线程主体类
    private int ticket=10;						//卖票
    @Override
    public String call() throws Exception{
        for(int x=0;x<100;x++){
            if(this.ticket>0){					//还有票可以出售
                System.out.println("卖票,ticket="+this.ticket--);
            }
        }
        return "票已卖光!";						//返回结果
    }
}

When the definition of the multi-threaded main class is completed, the Thread class should be used to start multi-threading, but no constructor is defined in the Thread class to directly receive the Callable interface object instance, and due to the need to receive the return value of the call () method, Java provides a java.util.concurrent.FutureTask <V> class, defined as follows:

public class FutureTask<V>
extends Object
implements RunnableFuture<V>

Insert picture description here
Insert picture description here
Example: Start multiple threads

package Project.Study.Multithreading;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyThread3 implements Callable<String>{
    private int ticket=10;
    @Override
    public String call() throws Exception{
        for(int x=0;x<100;x++){
            if(this.ticket>0){
                System.out.println("卖票,ticket="+this.ticket--);
            }
        }
        return "票已卖光!";
    }
}
public class Test3 {
    public static void main(String []args)throws Exception{
        MyThread3 mt1=new MyThread3();					//实例化多线程对象
        MyThread3 mt2=new MyThread3();
        FutureTask<String>task1=new FutureTask<>(mt1);
        FutureTask<String>task2=new FutureTask<>(mt2);
        //FutureTask是Runnable接口子类,所以可以使用Thread类的构造来接收task对象
        new Thread(task1).start();						//启动第一个多线程
        new Thread(task2).start();						//启动第二个多线程
        //多线程执行完毕后可以取得内容,依靠FutureTask的父接口Future中的get()方法实现
        System.out.println("A线程返回的结果:"+task1.get());
        System.out.println("B线程返回的结果:"+task2.get());
    }
}
//结果:
//卖票,ticket=10
//卖票,ticket=9
//卖票,ticket=10
//卖票,ticket=9
//卖票,ticket=8
//卖票,ticket=8
//卖票,ticket=7
//卖票,ticket=7
//卖票,ticket=6
//卖票,ticket=6
//卖票,ticket=5
//卖票,ticket=5
//卖票,ticket=4
//卖票,ticket=4
//卖票,ticket=3
//卖票,ticket=2
//卖票,ticket=1
//卖票,ticket=3
//卖票,ticket=2
//卖票,ticket=1
//A线程返回的结果:票已卖光!
//B线程返回的结果:票已卖光!

This program uses the FutureTask class to implement a subclass of the Callable interface. Since FutureTask is a subclass of the Runnable interface, you can use the start () method of the Tread class to start multithreading. When the thread execution is complete, you can use the get ( ) Method returns the execution result of the thread.

The operating state of the thread

Any thread generally has five states, namely: create, ready, running, blocked and terminated.
Insert picture description here

1. Create State

After creating a thread object in the program using the construction method, the new thread object is in a new state. At this time, it has the corresponding memory space and other resources, but it is still in an inoperable state.

2. Ready state

After creating a new thread object, call the thread's start () method to start the thread. When the thread starts, the thread enters the ready state. At this point, the thread will enter the thread queue and wait for the CPU service, which indicates that it already has the running conditions.

3. Running state

When the thread in the ready state is called and obtains processor resources, the thread enters the running state. At this time, the run () method of the thread object is automatically called.

4. Blocked state

Under certain special circumstances, such as being suspended or need to perform time-consuming input and output operations, a running thread will give up the CPU and temporarily suspend its execution and enter a blocked state. In the executable state, if you call sleep (), suspend (), wait () and other methods, the thread will enter a blocked state. When congested, the thread cannot enter the queuing queue. Only after the cause of the congestion is eliminated, the thread can be transferred to the ready state.

5. Termination status

After the thread calls the stop () method or the run () method, it is in a terminated state. The thread in the terminated state does not have the ability to continue running.

49 original articles published · Liked 25 · Visits 1522

Guess you like

Origin blog.csdn.net/weixin_45784666/article/details/104957664