This is the first day of my participation in Gwen Challenge

Time passed so fast, today is 61, a long time did not update the article, and become lazy! Challenge yourself with activities! Come on brothers! It shouldn’t be too much to celebrate Children’s Day with my brain and wallet hahaha

Java program is a natural multithreaded program, so learn Java, you must learn multithreading, in Android multithreading is still a lot of, today to understand some of the basic concepts of multithreading, and the life cycle of the thread

1. Basic concepts

1.1 Relation between number of CPU cores and number of threads

1.1.1 Number of CPU Cores

In a computer, the core is the processor and when we go and buy a computer, whether it’s a desktop or a laptop or a cell phone, we’re going to look at how many cores the Cpu isRight? So my computer has six cores, six processors, and in the early days of computers, the CPU didn’t have multiple cores, it had one core, and then why did it have multiple cores? Multi-core is because according to Moore’s law, the density of the transistor in the computer chip that can be doubled every 18 months, come to this point, since the memory in the CPU to 3 nm, to 3 nm will turn to be not moved, why did not move, I don’t know, involving quantum tunneling this thing, in order to continue to improve the computing speed, Puts forward the concept of multiple core, on a physical chip, we integrate multiple physical processor (CMP), CMP is put forward by Stanford university, single chip processor, also refers to many of its core idea is to massively parallel processor in the SMP (symmetric multiprocessor) are integrated into the same chip, each processor parallel execution process

1.1.2 Relation between number of CPU cores and number of threads

CPU cores: Threads = 1:1, they are one to one, the relationship between the number of threads is refers to, the running threads maximum number, such as my computer is six, my computer running threads at the same time, the largest number is 6, the number of threads is not our procedure in the process for how many threads, but there are also six nuclear CPU, but the number of threads can reach 12, How does this work? Intel’s hyper-threading technology allows you to take a physical CPU and simulate it as two logical cpus, one physical core for each logical core

1.2 CPU Time slice rotation Mechanism

In the process of our development, as if was not affected by the number of core, in the program, we think of a few threads up several threads, CPU rotary mechanism is the most simple, the oldest, the most fair, and also is a kind of algorithm is the most widely used mechanism, also known as RR scheduling, even if I had a CPU, there are one hundred threads in the implementation, But what the CPU gives us is. A hundred threads running at the same time. How does that workSo we split the CPU running time, let’s say 5ms per thread, very, very small 5ms, 5ms per thread, 100 threads running once, that’s 500ms, and for us, we might not feel it stopping, and because of this mechanism, it makes us feel like we’re starting a thread, It’s running at the same time, but it’s not really the case. The size of the time slice depends on the operating system, it depends on the Cpu. The Cpu rotates by time. In Java, can you tell the Cpu to specify a thread to execute

1.3 What is thread and what is process

Standard version: Process is the basic unit of resource allocation and scheduling in the operating system, thread is the smallest unit of operation scheduling in the operating system. The program started by our computer is a process, such as wechat, AndroidStudio and IDEA. In terms of conceptual scale, process is larger than thread, and thread cannot exist alone. A thread must be attached to a process to exist. If a thread is alive in a process, the process is alive. Threads in a process share all the resources in the process memory, CPU and IO. Threads are the minimum unit of CPU scheduling and in operating systems, you can’t have more than 1000 new threads on Linux, you can’t have more than 2000 new threads on Windows,

1.4 Parallelism and concurrency

The technical term is a little tricky, parallelism, is the maximum number of threads that can run at the same time, Intel’s quad core parallelism is 8, it can run 8 threads at the same time concurrency refers to the number of tasks that can be processed per unit of time, it has to be time dependent, for concurrency, it doesn’t make sense to get out of unit of time, For example, if a CPU executes 100 time slices per second, its concurrency is 100. If another CPU executes 200 time slices per second, its concurrency is 200

1.5 Implications, benefits, and considerations of high concurrency programming

Without high concurrent programming, we are not able to fully maximize the ability to take advantage of the multicore multi-threading, use high concurrent programming, can improve the responsiveness of our programs, such as thunderbolt, provides a multi-threaded download, can high concurrent programming in our programming, make our programs modular, asynchronous, And simplification, but in concurrent programming, the most important thing to pay attention to is safety, because threads in the same process are sharing all the resources of the process, it is likely to cause thread safety problems and deadlock problems, in Linux or Windows, too many threads open, will cause memory depletion. When the thread cedes the CPU, the operating system stores the current data state to memory or disk. When it is the thread’s turn again, it takes it out and loads it in. This is a context switch. A context switch requires about 20000 CPU time period, this is also very consumption of CPU resources, if the thread is overmuch, will be a large number of context switches, is likely to cause a situation like this, if you had 100 threads, using time slice rotation mechanism, the amount of time is far greater than you one by one thread execution time, So multithreading to use well, we have to consider to be comprehensive

2. Learn about Threads in Java

public class OnlyMain {
    public static void main(String[] args) {
        // Virtual machine thread management interface
        ThreadMXBean threadMXBean= ManagementFactory.getThreadMXBean();
        // Get thread information
        ThreadInfo[] threadInfos=threadMXBean.dumpAllThreads(false.false);
        for (ThreadInfo threadInfo:
             threadInfos) {
            System.out.println("["+threadInfo.getThreadId()+"]"+""+threadInfo.getThreadName()); }}}Copy the code

If I execute the main method, how many threads will it execute? If you’re interested, run through the code to verify that it will execute six threadsWhy do I only execute one main method? Why do I have six threads executing main

When we were learning Java, Java was an object-oriented language, and the parent class of all the classes was Object, and inside Object there was a method like thisWe have an object in a resource recycling, will rewrite the method, then the operation of the recycling, in this method, this method will be performed by the finalizers this thread, but sometimes will find that the finalize method may not perform, guide, some about the resources that the object will not be recycled, Why is that? Finalizer thread is a daemon thread. Finalizer thread and finalize thread live and die together. It is very likely that finalize thread will hang and Finalizer will hang before finalize method is executed

2.1 Two ways to start a thread

Java programs are inherently multithreaded. You can start a new thread by:

  • Thread class
  • Implement interface Runnable
  • Implementation interface Callable has a return value
/*** * Several ways to start threads */
public class NewThread {
    // Inherits from Thread
    private static class UseThread extends Thread{
        @Override
        public void run(a) {
            super.run();
            System.out.println("UseThread: I'm running"); }}// Implement the Runnable interface
   private static class  UseRun implements Runnable{

        @Override
        public void run(a) {
            System.out.println("UseRun: I'm running"); }}// Implement the callable interface, allowing a return value
    private static class UseCall implements Callable<String>{
        @Override
        public String call(a) throws Exception {
            System.out.println("UseCall: I'm running");
            return "CallResult"; }}public static void main(String[] args) throws ExecutionException, InterruptedException {
        UseThread useThread=new UseThread();
        useThread.start();
        UseRun useRun=new UseRun();
        new Thread(useRun).start();
        UseCall useCall=new UseCall();
        FutureTask<String> futureTask=new FutureTask<>(useCall);
        newThread(futureTask).start(); System.out.println(futureTask.get()); }}Copy the code

The way Callable and Runnable are implemented can actually be viewed as a way, because when you start a thread Callable is put into FutureTask, so let’s see what FutureTask is and it’s a generic class that implements RunnableFuture as a generic interface, RunnableFuture in turn inherits Runnable and Future, so we can think of Runnable and Callable as a way, how does Callable get the return value?

Futuretask.get () returns the return valueLet’s look at implementationIt determines whether the state of the task is complete, and if it is not, it enters the wait to complete method

 private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            if (s > COMPLETING) {
                if(q ! =null)
                    q.thread = null;
                return s;
            }
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                q = new WaitNode();
            else if(! queued) queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                LockSupport.park(this); }}Copy the code

It’s going to wait until it’s done and then it’s going to execute the report method, so let’s look at the report method

And then let’s look at the Run method

    public void run(a) {
        if(state ! = NEW || ! UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if(c ! =null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if(ran) set(result); }}finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if(s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); }}Copy the code

It assigns the return value of Call to the outcome via the set method, and returns the outcome on GET

    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final statefinishCompletion(); }}Copy the code

That’s how we get the return value of the Callable. Here we need to distinguish between Thread and Runnable. Thread is the only abstraction of an operating system Thread, and Runnable and Callable are abstractions of a task

2.2 Thread-safe stop

After interruption () or isInterrupted (), static method interrupted ()? We want to deep understanding of these methods Under normal circumstances, the Thread’s run method is performed, or throws exceptions, this Thread is completed, they stopped, it is usually, but we often because of business needs, need to meet certain conditions, to manually stop the Thread, what should we do this time? So let’s go back to the code and see what methods are in Thread, okayWe see stop (), destroy (), and suspend (), but these methods are annotated by @deprecated. The JDK tells us not to use the thread’s suspend function suspend (), which does not release resources while suspending. Such as it got a lock in the execution, hang when he won’t release the lock, so it is likely to lead to a deadlock problem threads stop stop () function, this function is extremely brutal, you call the function, he would immediately kill this thread, he won’t tube you the thread of the release of resources is normal, Such as you write a document in one thread, wrote half of the time you call this method, cause the file can not be normal, and the operating system in the thread of resource file handle what has not been released resume was to raise the hung thread, and suspend matching use In fact, we at the time of termination of the thread, so there are several methods can be usedInterrupt terminates the thread, interrupted isInterrupted gets whether or not the thread terminates, interrupt terminates the thread in a cooperative way not in a preemptive way, so without saying more about the code,

public class EndThread {
    private static class UseThread extends Thread{
        @Override
        public void run(a) {
            super.run();
            while(true){
                System.out.println("EndThread:emmmmmm"); }}}public static void main(String[] args) throws InterruptedException {
        UseThread useThread=new UseThread();
        useThread.start();
        Thread.sleep(30); useThread.interrupt(); }}Copy the code

This code starts a new thread in the main thread. The main thread sleeps for 30ms and calls useThread interrupt ()

   private static class UseThread extends Thread{
        @Override
        public void run(a) {
            super.run();
// while(true){
            System.out.println("EndThread:"+isInterrupted());
            while(! isInterrupted()){ System.out.println("EndThread:emmmmmm");
            }
            System.out.println("EndThread:"+isInterrupted()); }}Copy the code

We see that it stops and it breaks out of the loop In Java, Thread interrupt simply changes the interrupt signal from false to true. It does not terminate the Thread unless the Thread does anything to the interrupt signal. Therefore, the interrupt is cooperative, not preemptive. For example, if the status of a Thread isInterrupted by a Thread member (isInterrupted) or a static method (interrupted), what is the difference between the two methods? He’s going to get that state and set that state to false and the code up there, it’s going to print true, so let’s change the code again and take a look

 private static class UseThread extends Thread{
        @Override
        public void run(a) {
            super.run();
// while(true){
            System.out.println("EndThread:"+isInterrupted());
// while(! isInterrupted()){
            while(! Thread.interrupted()){ System.out.println("EndThread:emmmmmm");
            }
            System.out.println("EndThread:"+isInterrupted()); }}Copy the code

2.3 Understanding the run() and start() of Thread

There’s no difference between the run method and the member method in our ordinary class. There’s nothing to click on the start method. The start method finally executes the native method stat0, so we can call run

  private static class UseThread extends Thread{
        @Override
        public void run(a) {
            super.run();
            for(;;) { System.out.println(Thread.currentThread().getName());try {
                    Thread.sleep(1000);
                } catch(InterruptedException e) { e.printStackTrace(); }}}}public static void main(String[] args) {
        UseThread beCalled=new UseThread();
        beCalled.setName("beCalled");
        beCalled.run();
    }
Copy the code

The above code can also be called normally, output resultsBut when we change run to startThread is linked to the operating system Thread only after it has executed the start. If it does not execute the start, it is no different from normal classes. The same Thread cannot execute the start twice. The start of execution of the second time will be thrown. Java lang. IllegalThreadStateException

2.4 Join and yield() methods for Thread

Learn about the life cycle of threadsAfter a thread in the execution start method may not perform, it will enter the ready state, waiting for the operating system scheduler, operating system, make it perform it, execute the join method can get the executive power, to the running state, performs yield in running state, will enter the ready state, waiting for the executive power of CPU, A path (sleep) will enter the blocking state, while a path (Interrrupt) will enter the ready state. A path (wait) will enter the blocking state, while a path (wake up) will enter the ready state

The join method can be understood as to jump the queue, a simple example Xuan xuan is a thread, he will go to the microwave oven to hot meals, microwave oven can be as a CPU, a hot meal is a task, hot food hot for 5 minutes, I need when I hot to 2 minutes, my goddess, I can let my goddess hot meals, the goddess of the thread after the join, Goddess can hot meals, and I can only after the goddess of hot meal, I can continue to hot meals, the goddess of heat to the half of the time her boyfriend also come over and join the goddess and her boyfriend, hot meal that I have to wait for her boyfriend, her after a hot, I can continue to heat my rice yield method, is I’m a hot meal, and then I take the food out, Rob the microwave with the goddess and the girl’s boyfriend, and the one who grabs the microwave gets to heat up the meal

2.5 Thread sleep() and Wait ()

The sleep method means that the thread sleeps, blocks the thread, and continues to execute when the time is up. The wait method means that a resource does not meet the requirement and waits until the resource meets the requirement. Then I use notify or notifyAll to wake up the resource. It looks similar to the sleep method, but the meaning is different

3. Summary

From the operating system said some basic concepts about CPU and thread, and then the main play or Java thread, respectively from the start and end, and its life cycle said, hope to write things to help you, hope big guys a key three connect!