Threads and processes

1. What is a process?

The running program is called process. Process is the basic unit for the system to allocate resources. PID is used to distinguish processes.

2. What is a thread?

Thread is an execution path in a process, and it is also the basic scheduling unit of CPU. A process is composed of one or more threads, which complete different work and execute at the same time, which is called multithreading.

3. Difference between process and thread -- Interview Questions

① Process is the basic unit of operating system resource allocation. Thread is the basic scheduling unit of CPU.

② There is at least one process after a program runs.

③ A process can contain multiple threads, but at least one thread is required, otherwise the process is meaningless.

④ Data segment addresses cannot be shared between processes, but they can be shared between threads of the same process.

4. Why use threads?

In order to solve the problem of load balancing and make full use of CPU resources, in order to improve CPU utilization, multithreading is used to complete several things at the same time without mutual interference. In order to deal with a large number of IO operations or processing situations, it takes a lot of time, such as reading and writing files, view image acquisition, processing, display, saving, etc.....

Single core era:

In the single core era, multithreading is mainly to improve the comprehensive utilization of CPU and IO devices. For example, when there is only one thread, it will cause the CPU to calculate, and the IO device will be idle; CPU idle during IO operation. We can simply say that the utilization rate of both is about 50%. However, it is different when there are two threads. When one thread performs CPU calculation, the other thread can perform IO operation, so that the utilization of the two threads can reach 100% under ideal conditions.

Multi core era:

In the multi-core era, multithreading is mainly to improve CPU utilization. For example: if we want to calculate a complex task, if we only use one thread, only one CPU core will be used, and creating multiple threads can make multiple CPU cores used, which improves CPU utilization.

5. How to create a thread?

(1. Inherit Thread class and rewrite run method; 2. Implement Runnable interface; 3. Implement Callable interface)

① By inheriting the Thread class

package com.zd.demo04;
//Inherit Thread class
public class MyThread extends Thread{
    //Override run method
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("thread "+i);
        }
    }
}
package com.zd.demo04;

public class Test {
    public static void main(String[] args) {
        //Create a thread object
        MyThread myThread = new MyThread();
        //When the thread is started, the current thread competes with the main thread for CPU time slice at the same time
        myThread.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("main thread "+i);
        }
    }
}

② Implement Runnable interface

public class MyRunnable implements Runnable{
    
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"thread :"+i);
        }
    }
}
public class Test {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();//Thread task
        Thread a = new Thread(runnable, "thread  A");
        a.start();//Open thread
        //Thread object
        Thread b = new Thread(runnable, "thread  B");
        b.start();//Open thread
        for (int i = 0; i < 10; i++) {
            System.out.println("main thread "+i);
        }
    }
}

Example: buy 100 tickets in four windows

package com.zd.demo06;
//Example: buy 100 tickets in four windows
public class TickRunnable implements Runnable{
    private int ticket=100;
    @Override
    public void run() {
        while (ticket>0){
            System.out.println(Thread.currentThread().getName()+"Bought a spare one:"+--ticket);
        }
    }

    public static void main(String[] args) {
        TickRunnable runnable = new TickRunnable();
        Thread a = new Thread(runnable, "window A");
        Thread b = new Thread(runnable, "window B");
        Thread c = new Thread(runnable, "window C");
        Thread d = new Thread(runnable, "window D");
        a.start();//Open thread
        b.start();
        c.start();
        d.start();
//Test results: the same ticket is bought by multiple windows, and there are negative tickets. Because of thread safety issues
    }
}

6. Name the thread and get the thread name

1. Get thread name

①this.getName() must be a subclass of Thread

②Thread.currentThread.getName(); Get thread name anywhere

2. Name the thread:

① By calling the setName method, the object of this class must be the object of Thread

② By construction method

7. Common methods in threads

① public static void sleep(long) sleep

②public  static  void  yield(); Give up this time slice, return to the ready state and participate in the competition for the next time slice

③ public void join() allows other threads to join the current thread until other threads are allowed to end. Only the current thread can run

④setPriority(); Set the priority. The greater the value of 1-10, the greater the probability of obtaining CPU. The default value is 5

⑤ setDaemon(): set the daemon thread. The daemon thread will not end until all foreground threads end.

Keywords: Java Back-end

Added by skyxmen on Wed, 15 Dec 2021 21:37:01 +0200