This is the third day of my participation in Gwen Challenge

This article is participating in “Java Theme Month – Java Development in Action”, see the activity link for details

What is a thread

Process of 1.

To talk about threads, what is a process

Concept:

Process is a running activity of a program on a data set in a computer. It is the basic unit of resource allocation and scheduling in the system and the basis of operating system structure. In the early process-oriented computer architecture, the process is the basic execution entity of the program. In modern thread-oriented computer architectures, processes are containers for threads. A program is a description of instructions, data and their organizational form, while a process is an entity of the program. — Baidu Encyclopedia

A process is an independent unit that has resources on the operating system and can run independently. Each process has its own piece of memory space, which contains the code and data space of each process. Switching between processes will cost a lot. To run an application on an operating system, a process is created to execute the application’s code

Thread 2.

Concept:

A thread (English: thread) is the smallest unit in which an operating system can schedule operations. It is contained within the process and is the actual operating unit within the process. A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel. In Unix System V and SunOS, they are also referred to as Lightweight processes, but more commonly referred to as kernel threads, while user threads are referred to as threads. — Baidu Encyclopedia

Threads did not exist in early operating systems, but were created to squeeze the CPU further. Thread is the basic unit of the CPU in the operating system can handle, a process with multiple threads, thread in the same process in the process of the sharing of code and data space, because each thread has its own independent operation of the stack and the program counter, so the switching cost between threads is small, can be through the switch threads, reduce the waiting time for IO obstruction

3. The difference between processes and threads

  1. Processes are the smallest unit of resource allocation and threads are the smallest unit of CPU scheduling
  2. A program must have at least one process, and a process must have at least one thread
  3. Processes are independent of each other. Threads in the same process share the memory space and resources of the process
  4. The overhead of switching between processes is high and the overhead of switching between threads is low

4. The relationship between processes and threads

  1. Threads must exist in a process
  2. The resources used by threads are resources assigned to processes by the operating system

5. Scheduling tasks for the operating system

Because CPU processing speed is very fast, most operating systems adopt the preemptive scheduling method of time slice rotation. When a process uses up its allocated time slice, it will be deprived of CPU usage, and the operating system will select the process with the highest priority to occupy the CPU. This allows multiple processes to run simultaneously, but they are not running at the same time. The same is true for task scheduling between threads

6. Diagram of the relationship between process and thread

Second, the use of threads

Code 1.

This is an example of instruction reordering, but how can threads be used

/ * * *@authorXXJ * * Thread test */
public class ThreadTest {
    static int a=0,b=0;
    static int c=0,d=0;
    public static void main(String[] args) throws Exception{
        Thread thread1=new Thread(new Runnable(){
            @Override
            public void run(a) {
                c=1; a=d; }}); Thread thread2=new Thread(new Runnable(){
            @Override
            public void run(a) {
                d=1; b=c; }}); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println("a:"+a+" b:"+b+" c:"+c+" d:"+d); }}Copy the code

Step 3.

  1. You first need to create an implementation object for the Runnable interface. As you can see, I’ve overridden its run method. Normally you’d define a class that implements this interface
  2. To create a Thread object, place the implementation object of the Runnable interface you just created into the Thread constructor
  3. To start the Thread, call the start method of the Thread object

3. Common methods of Thread

  1. Start (), which starts the thread. With this method, the thread changes from the new state to the ready state
  2. With sleep(), the thread changes from running/ready to blocked and returns to ready when sleep time is up
  3. Wait (), suspends the thread. With this method, the thread changes from a running/ready state to a blocked state, which the thread object can use directly
  4. Notify () and notifyAll() wake up threads and change a thread that has used wait from a blocked state to a ready state

4. Callable threads

/** * test for thread with return value */
public class CallableTest {
    public static void main(String[] args) {
        2. Create an instance of the Callable implementation class
        MyCallable callable=new MyCallable();
        // create an instance of FutureTask<> with the same data type as the Callable implementation class
        // Pass the callable implementation class instance into the constructor
        FutureTask<Integer> futureTask=new FutureTask<>(callable);
        //4. Create a Thread instance and pass in the FutureTask instance
        Thread thread=new Thread(futureTask);
        //5. Start thread
        thread.start();
        try {
            Use futureTask.get() to get the value returned by the thread
            System.out.println("Value returned by child thread:"+futureTask.get());
        } catch(Exception e) { e.printStackTrace(); }}//1. Create an implementation class that implements Callable<>. You can fill in any data type in <>
    public static class MyCallable implements Callable<Integer> {
        @Override
        public Integer call(a) throws Exception {
            int i=0;
            for (i=0; i<10; i++){ System.out.println(Thread.currentThread().getName()+"Thread"+i);
            }
            // Remember the return value
            returni; }}}Copy the code

Third, the running status of the thread

  1. New state: When a thread instance is created, it enters the new state
  2. Ready: When a thread calls the start method, it is started and ready to get CPU resources at any time
  3. Running state: The thread will run the code in the run method only if it is in the ready state and then obtains CPU resources
  4. Blocked: a thread enters a blocked state when its allocated time slice is up, or when it encounters AN IO block and actively calls some methods. The ready state is reached when CPU resources are reallocated, I/O is ready, and the thread is awakened by an active call to a method
  5. Dead: When a thread enters a dead state, its entire life cycle ends

4. Composition of threads

1. Thread identifier (ThreadID)

ThreadID is the identifier for each thread. If two threads have the same ID, they are the same thread

2. Thread local Storage (TSL)

TSL (thread Local Storage) is the private memory space of each thread and is independent of the shared memory space of the process

3. Program counter (PC)

PC full name Program Counter, Program Counter stores the address of the Program instruction, when the CPU executes this thread, it will find the corresponding instruction according to the address of the Program Counter, and then let the Program Counter point to the address of the next instruction.

4. The stack

This stack is also a thread-private stack, used to execute instructions from thread methods

Fifth, thread safety

Thread safety is a concept in computer program code in multithreaded programming. In the parallel execution of programs with multiple threads with shared data, thread-safe code ensures that each thread can execute normally and correctly through the synchronization mechanism without data contamination and other unexpected situations. — Baidu Encyclopedia

Thread safety is concerned with whether or not a single data will be contaminated when multiple threads are running, usually the shared data in the shared memory of the process. When a thread executes an instruction, it copies the shared data in the memory to the local computer, performs operations, and then allocates data back to the memory. If multiple threads copy data at the same time, only one thread allocates data back to the memory, which causes data pollution. The solution: Synchronized /Lock or volatile, Lock or make the data visible so that it doesn’t pollute the data. This allows per-thread operations to have atomic rows, somewhat like things in a database.

Six, summarized

Threads must be attached to a process and occupy its resources and memory space, but each thread has its own private memory space. Using threads can improve CPU utilization because switching between threads is less expensive than switching between processes, but thread-safety concerns need to be addressed

— — — — — — — — — — — — — — —

The more you know, the more you don’t know.

If you have any questions about the content of this article, please comment directly or email me. If you think the writing is good, a “like” is also to support me

Shall not be reproduced without permission!

Wechat public account [programmer Xu Xiaobai], you can follow the first time to read the latest articles. I prepared 50 high-frequency school recruitment interview questions, as well as a variety of Java learning materials.