Up! It turns out that this is the correct implementation of Java multithreading!

Keywords: Java Back-end

Routine: realize slow character output

public class ThreadDemo1 {
    public static void main(String[] args) throws InterruptedException {
        String content = "Others say you can't because he can't do it himself. You should try your best to protect your dreams. Those who laugh at you will fail," +
                "They want to make you like them. If you have a dream, try to realize it, that's it.";
        for (char item : content.toCharArray()) {
            System.out.print(item);
            //Execution to this line sleep for 200 milliseconds
            Thread.sleep(200);
        }
    }
}

Advantages of multithreading - increase running speed

You can observe the following multithreading routine to experience how to increase the running speed when multithreading.

The running results of this code are as follows:

It can be seen that the advantages of multithreading can increase the running speed and shorten the running time.

Thread creation method, hands-on contact thread (three types and six types)

Class 1: inherit Thread class to realize Thread creation (2 creation methods)

Class 1: inherit Thread class creation method 1

public class ThreadDemo3 {
    static class MyThread extends Thread {
        @Override
        public void run() {
            //Tasks performed by threads
            System.out.println("Thread Name: " +
                    Thread.currentThread().getName());
        }
    }
    public static void main(String[] args) {
        System.out.println("Name of the current thread (main thread):" +
                Thread.currentThread().getName());
        //Thread created
        Thread t1 = new MyThread();
        //Run thread
        t1.start();
    }
}

The code executes as follows

Class 1: inherit Thread class creation method 2

public class ThreadDemo4 {
    public static void main(String[] args) {
        System.out.println("Name of the current thread (main thread):" +
                Thread.currentThread().getName());
        Thread thread = new Thread() {
            @Override
            public void run() {
                //Tasks performed by threads
                System.out.println("Thread Name: " +
                        Thread.currentThread().getName());
            }
        };
        thread.start();
    }
}

The code executes as follows

Disadvantages of the first creation method (inheriting Thread class):

In the design of Java language, only single inheritance can be realized. If this class inherits Thread class, it cannot inherit other classes.

Class 2: thread creation by implementing Runnable interface (3 creation methods)

It makes up for the disadvantage of the first type of creation method, that is, Java can not inherit more, but can implement multiple interfaces

Creation method ①:

The code executes as follows

Creation method ②: use anonymous inner classes to implement threads

public class ThreadDemo6 {
    public static void main(String[] args) {
        System.out.println("Name of the current thread (main thread):" +
                Thread.currentThread().getName());
        //Implementing threads using anonymous inner classes
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread Name: " +
                        Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

The code executes as follows

Creation method ③: implementation method of lambda + anonymous Runnable

public class ThreadDemo7 {
    public static void main(String[] args) {
        System.out.println("Name of the current thread (main thread):" +
                Thread.currentThread().getName());
        //Fixed writing in JDK8
        //Implementation of lambda + anonymous Runnable
        Thread thread = new Thread(() -> {
            System.out.println("Thread Name: " +
                    Thread.currentThread().getName());
        });
        thread.start();
    }
}

The code executes as follows

Class 3: thread creation by implementing the Callable interface (one creation method)

The advantage is that you can get the result after thread execution.

The execution result of this code is as follows

Thread hibernation (there are three implementations)

Implementation method ①
Advantages: high accuracy.
Disadvantages: when the sleep time is too long, the code writing is more complex.

public class ThreadDemo9 {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Start time: " + new Date());
        //Sleep for 1s
        Thread.sleep(1000);
        System.out.println("End time: " + new Date());
    }
}

The code execution results are as follows

When hibernating for a long time, implementation method ② and implementation method ③ can be used.
Implementation method ②

The execution result of this code is as follows

Implementation method ③

public class ThreadDemo9 {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Start time: " + new Date());
        //Sleep for 1s
        Thread.sleep(TimeUnit.SECONDS.toMillis(1));
        System.out.println("End time: " + new Date());
    }

The execution result of this code is as follows

Typical example: use two threads to print "AABBCCDD".

Problem solving idea: use multithreading + thread sleep to complete the problem requirements

The execution result of this code is as follows

Summary

Process is the smallest unit of system resource allocation, and thread is the smallest unit of system scheduling. Resources can be shared between threads in a process. Each process has at least one thread, the main thread.

Posted by monkeytooth on Wed, 20 Oct 2021 10:37:24 -0700