Processes and threads

Posted by xeirus on Wed, 02 Feb 2022 11:07:43 +0100

Processes and threads

What are processes and threads? What is the difference between the two?
How to implement threads?
Methods commonly used in threads?
What are the states in the thread?
Thread scheduling problem?
Thread safety issues?
wait and notify methods in Object class?
Producer and consumer model

Process and thread and their differences

A process is an application or software
A thread is an execution unit of a process.
A process can have multiple threads. A thread corresponds to a stack, and there is a gap between stacks
Independent of each other.

Method of implementing thread

 1. Write a class that directly inherits Java Lang. thread, override the run method.

public class ThreadTest01 {
    public static void main(String[] args) {
        //The method here is the main method, which belongs to the main thread and runs in the main stack
        MyThread myThread = new MyThread();
        //Start thread
        //The function of the start method is to start a branch thread and open up a new stack space in the JVM. After the code task is completed, it will end immediately
        //This code is to open up a new space. As long as the new stack space is opened up, the start method will end and the thread will start successfully.
        //The run method is at the bottom of the branch stack and the main method is at the bottom of the main stack. Run and main are equal.
        //Note: calling the run method directly will not start the thread and will not allocate a new branch stack.
        myThread.start();
        //The code here is still running in the main stack
        for(int i = 0;i<1000;i++){
            System.out.println("Main thread---"+i);
        }
    }
}
class MyThread extends Thread{
    public void run(){
        //Write a program that runs in the branch stack
        for(int i = 0; i < 1000; i++){
            System.out.println("Branch thread---"+i);
        }
    }
}

Code analysis: create a thread object and call the thread object's start method to open it.
Thread
The function of the start method: start a branch thread and open up a new stack in the JVM
Space, this code will end in an instant after the task is completed.
Note: calling the run method directly will not start the thread and will not allocate a new branch stack.
 2. Write a class to implement Java Lang. runnable interface, which implements the run method.

public class ThreadTest02 {
    public static void main(String[] args) {
        //Create a runnable object
        MyRunnable myRunnable = new MyRunnable();
        //Encapsulate the runnable object into a thread object
        Thread thread = new Thread(myRunnable);
        thread.start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("Main thread"+i);
        }
    }
}
//This is not a thread class, but a runnable interface
class MyRunnable implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i<1000;i++) {
            System.out.println("Branch thread" + i);
        }
    }
}

Methods commonly used in threads

 1.currentThread() method: used to obtain the current thread object. It is a static method

Thread currentthread = Thread.currentThread();
        System.out.println(currentthread);

 2.getName() method: used to get the name of the thread
setName() method: used to modify the name of the thread

//MyThread7 is a thread class
        MyThread7 myThread2 = new MyThread7();
        myThread2.setName("tttt");

        System.out.println( myThread2.getName());
        myThread2.start();

Note: when the Thread has no name set, the default name is Thread-0, Thread-
1 wait
 3.sleep() method: it is a static method, and the parameter is milliseconds. The function is to make the current thread enter
Enter sleep, enter the blocking state, give up the occupied CPU time slice and give it to other threads
Use

public static void main(String[] args) {
        //Let the main thread sleep for 5 seconds
        try {
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Output after 5 seconds
        System.out.println("hello world!");
    }

Status in thread

The status is divided into five categories: new status, ready status, running status, blocking status and death status
Status
New status: the newly created thread object is a new object
Ready state: the thread is in ready state after calling the start method. Ready status is also called
Runnable state, indicating that the current thread has the right to seize the CPU time slice. When a line
After the process grabs the CPU time slice, it starts to execute the run method.
Running state: the thread is running after calling the run method. CPU occupied before
After the time slice is used up, it will return to the ready state and continue to rob the time slice. When it is used up again
After grabbing the CPU time slice, it will re-enter the run method, and then continue to execute the last code.
Note: running between threads is alternating between multiple threads.
Dead state: when the execution of run ends, the thread enters the dead state.
Blocking state: when a blocking event is encountered, it enters the blocking state. For example, sleep method
Or receive user keyboard input. When a thread in a blocked state abandons the previously occupied CPU
Between pieces. You need to return to the ready state again to grab the CPU time slice.

Introduction to thread scheduling problem

Thread scheduling model:
    1. Preemptive scheduling model: which thread has higher priority and when it grabs the CPU
The probability of inter slice is higher. java adopts preemptive scheduling model.
    2. Even fraction scheduling model: evenly allocate CPU time slices, and each thread occupies
The length of CPU time is the same as that of chip.
Methods related to thread scheduling:
setPriority(int newPriority): sets the priority of the thread
getPriority(): get the priority of the thread
Supplement: the lowest priority is 1, the default priority is 5, and the highest priority is 10;
Higher priority may get more CPU time slices.

static void yield(): pause the currently executing thread object and execute
Line other threads. After executing this method, it will not enter the blocking state. But make
The current thread returns from the running state to the ready state.

void join(): merge threads, and then enter another thread until the thread is blocked
The original process is not carried out until the process is completed
Note: the sleep method and the join method will enter the blocking state.

Introduction to thread safety

In the development process, our projects are running in the server, and the server
The definition, creation and startup of threads have been implemented,
We don't need to write any of this code. The most important thing is that the program you write needs to be put in one place
It runs in a multithreaded environment, so we need to pay attention to the fact that these data are multithreaded and
Whether it is safe in the environment.

When will there be a security problem?
    1. Multithreading concurrency 2 Shared data 3 Shared data has modification behavior.
For example, our daily ATM withdrawal.
Thread programming mode:
    1. Asynchronous programming model: thread 1 and thread 2 execute their own, and no one knows
This model is called asynchronous programming model
    2. Synchronous programming model: thread 1 and thread 2. When thread 1 executes, it must
You have to wait for the end of thread 2 execution, or when thread 2 executes
Wait, you must wait for thread 1 execution to end. A wait occurred between two threads
Relationship. Low efficiency, but data security.

Thread safety solution: threads are queued for execution and cannot be concurrent, which is called thread synchronization
Step execution. Some efficiency will be sacrificed in this process.

Syntax of thread synchronization mechanism: synchronized (shared object) {thread synchronization code
Block}, the data in parentheses is quite critical. This must be the number shared by multiple threads
What is written in () depends on which threads we want to synchronize. That is, shared objects.

Synchronized can be written in two ways:
    1. Use Synchronized on the instance method. At this time, the shared object must be
     this. And the synchronization code block is the whole method body One object, one lock.
    2. Synchronized is used on the static method, which means to find the class lock, and the class lock is permanent
There's only one.
Add: synchronized will reduce the efficiency of program execution and poor user experience,
The system user throughput (concurrency) is reduced and the user experience is poor.

Therefore, we try our best to do the following:
     1. Try to use local variables instead of instance variables and static variables
     2. If it must be an instance variable, you can consider creating multiple objects,
In this way, the memory of instance variables is not shared.
     3. If you cannot use local variables, you cannot create multiple objects
Time can only choose synchronized, thread synchronization mechanism.

wait and notify methods in Object class

First: the wait method and notify method are not thread objects, but any one in java
Both java objects have methods, because these two methods are in the Object class
It comes with it. The wait method and notify method are not called through a thread object
Yes.

Second, the function of the wait method: Object obj = new Object();
     o.wait( ); Indicates to put the thread active on the O object into a wait state
State, waiting indefinitely until awakened.
Third: the notify method wakes up the waiting thread.

Producer and consumer model

public class ThreadTest06 {
    public static void main(String[] args) {
   //Create a warehouse object and share it
    List list = new ArrayList();

    //Create two thread objects
        Thread t1 = new Thread(new Product(list));
        Thread t2 = new Thread(new Consumer(list));

        t1.setName("Build thread");
        t2.setName("Consumption thread");

        t1.start();
        t2.start();
    }
}
//Build thread
class Product implements  Runnable{
    private List list;
    public Product(List list){
        this.list = list;
    }
    @Override
    public void run() {
    //Continuous generation (continuous production using dead cycle simulation)
        while(true){
            synchronized (list){
                if(list.size()> 0){
                    //The current thread enters the waiting state
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //When the program is executed to this point, it indicates that the list set is empty and can be generated
                Object obj = new Object();
                list.add(obj);
                System.out.println(Thread.currentThread().getName()+"----->"+obj);
                //Wake up the consumption thread for consumption
                list.notify();
            }

        }

    }
}
//Consumption thread
class Consumer implements Runnable{
    private List list;
    public Consumer(List list){
        this.list = list;
    }
    @Override
    public void run() {
    //Always consumption
        while (true){
            synchronized (list){
                if(list.size() == 0){
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //When the program is executed here, it shows that there are elements in the list set that can be consumed
                Object obj = list.remove(0);
                System.out.println(Thread.currentThread().getName()+"--->"+obj);
                list.notify();
            }
        }
    }
}

Topics: Java Multithreading