Multithreading review-01

I haven't been able to tweet for a long time. Because of the epidemic, Xiaobian also failed to go to school. She has been staying at home for a long time and has been trying to write down tweets, but she doesn't know what. After looking at the previous section, I plan to improve the bricklaying series first. So today, I will review some basic knowledge of Java multithreading with you and demonstrate some programs I wrote.
In the multi-threaded part, I plan to divide it into two parts: the first part introduces the basic concept of multi-threaded and how to construct it; the second part introduces the existing problems and handling methods between multi-threaded.
Next, let's move on to today's topic - the basic concept of multithreading and how threads are constructed
When it comes to multithreading, we have to talk about multithreading first. Although there is a word difference between process and thread, they are different concepts. We first give the definition of process and thread, and then analyze the difference and relationship between them in detail.
A process is an execution process of a program about a data set, and it is the basic unit of resource allocation and protection of the operating system.
Thread is an independent entity in a process, and it is the basic unit of processor scheduling and dispatching. Threads are part of a process, and each process allows multiple threads to execute concurrently. All threads of the same thread share the memory space and resources obtained by the process, but do not own the resources.
From the definition, the scope of a process is larger than that of a thread. A process can contain many concurrent execution threads. That is to say, when the CPU executes a process every time, it is actually scheduling and processing the concurrent execution threads in the process.
Threads have five states: new, ready, running, blocking, and terminating. After the thread is created, it is in the ready state. When the processor is obtained, it is in the running state. During the running, it is in the blocking state due to the waiting condition.
As for the scheduling of threads, because only one thread can occupy the processor at any time, when there are multiple threads in the ready state, they are queued for processing resources. Therefore, thread scheduling is needed. Thread scheduling adopts the method of deprivation, which has two main principles: first, high priority thread can deprive low priority thread from running, and the priority of thread describes the priority of thread execution. Second, when the running thread time is used up, it is deprived of the processor. This thread scheduling principle (deprivation principle) can avoid a thread monopolizing the processor for a long time, and provide better services for threads.
Let's talk about the construction method of multithreading in java.
There are two main methods to construct multithreading in Java: runnable interface and thread class. Runnable interface contracts the execution method of thread (i.e. run() method). Thread class provides the methods to create, manage and control thread objects.
Here is the local method declaration of Runnable interface and Thread class:

Runnable Interface:
public interface Runnable{
     public abstract void run();//Thread body describing thread operation
}

Thread class

Thread Class:
public class Thread extends Object implements Runnable{
     public Thread();
     public Thread(String name);
     public Thread(Runnable target);
     public Thread(Runnable target, String name);//Specify thread name and target object

     public abstract void run();//Thread body describing thread operation
     public final String getName();//Return thread name
     public final void setName(String name);
     public static int activeCount();//Returns the number of currently active threads
     public static Thread currentThread();//Returns the currently executing thread object
     public String toString();
     public void start();//Start thread object
}

The above two types can be used to construct threads. The main differences between them are as follows:
1. Inherit Thread class. Declare that a Thread class inherits the Thread class and overwrites the run() method. The point of this method is that the object of the Thread class is a Thread object and has a Thread body. The disadvantage is that it is not suitable for multiple inheritance.
2. Implement the Runnable interface. Declare a Thread class to implement the Runnable interface. The object created by this class is not a Thread object. It is used as the target pair of a Thread object. Therefore, you need to declare a Thread class object at the same time.

Priority of thread object
java provides Thread priority level of 10, which is represented by 1-10 respectively. The default value is 5. The Thread class declares the following three public static constants that represent priority:

  public static final int MIN_PRIORITY = 1    //Lowest priority
  public static final int MAX_PRIORITY = 10   //Highest priority
  public static final int NROM_PRIORITY = 5   //Default Priority 

You can get and set thread priority by:

  public final int getPriority()              //Get thread priority
  public final void setPriority(int priority) //Set thread priority

The life cycle of a thread object
In java, thread objects have the following six states
Thread status description:
1. NEW status. The thread object created by new Tread() is in NEW state, and the system does not allocate resources for it.
2. Operation state. From the perspective of the operating system, after the newly created thread starts, it enters the ready state, and then the operation system schedules the execution to the running state.
3. Blocking state and waiting state. A running thread cannot continue to run for some reason, entering blocking or waiting state. Threads in blocked or wait state cannot execute, even if the processor is idle. Only when the cause of blocking is eliminated, or waiting conditions are met, can the thread turn to running state.
4. Termination status. Thread object is terminated when it stops running and is not revoked. Thread running end or forced stop can make the thread enter termination state.
State and state change of java thread object:

Here is an example I wrote about multithreading bank accounts.

 1package ThreadTest;
 2
 3public class Account {
 4
 5    public String name;
 6    public double balance;
 7
 8    public Account(String name) {
 9        super();
10        this.name = name;
11        this.balance = 0;
12    }
13
14    public  void desposit(double value) {
15        this.balance += value;
16    }
17
18    public  void withdraw(double value) {
19        this.balance -= value;
20    }
21
22    public static void main(String[] args) {
23        System.out.println("brooke");
24        Account brooke = new Account("brooke");
25        new DespositThread(brooke, 10000).start();
26        new DespositThread(brooke, 10000).start();
27        new WithdrawThread(brooke, 1000).start();
28    }
29}
30
31class DespositThread extends Thread{
32    private Account account;
33    private double value;
34
35    public DespositThread(Account account, double value) {
36        super();
37        this.account = account;
38        this.value = value;
39    }
40
41    @Override
42    public void run() {
43        synchronized(account) {
44            double Nowbalance = account.balance;
45            account.desposit(value);
46            try {
47                sleep(1);
48            } catch (InterruptedException e) {
49            }
50            System.out.println(account.name + "account:existing"+Nowbalance+", Deposit"
51                    +value+",The balance is"+account.balance);
52        }
53    }
54}
55
56class WithdrawThread extends Thread{
57
58    private Account account;
59    private double value;
60
61    public WithdrawThread(Account account, double value) {
62        super();
63        this.account = account;
64        this.value = value;
65    }
66
67    @Override
68    public void run() {
69        synchronized(account) {
70            double Nowbalance = account.balance;
71            account.withdraw(value);;
72            try {
73                sleep(1);
74            } catch (InterruptedException e) {
75            }
76            System.out.println(account.name + "account:existing"+Nowbalance+", take out"
77                    +value+",The balance is"+account.balance);
78        }
79    }
80}

Keywords: Java

Added by MentalMonkey on Tue, 23 Jun 2020 06:59:07 +0300