Multithreading concept and three creation methods of multithreading

Multithreading related concepts

  • Threads are independent execution paths
  • When the program is running, even if it does not create its own thread, there will be multiple threads in the background, such as main thread and gc thread
  • main() is called the main thread, which is the entry of the system and is used to execute the whole program
  • In a process, if multiple threads are opened up, the operation of threads is scheduled by the scheduler. The scheduler is closely related to the operating system, and the sequence cannot be interfered by human beings
  • When operating on the same resource, there will be a problem of resource grabbing, and concurrency control needs to be added
  • Threads will bring additional overhead, such as cpu scheduling time and concurrency control overhead
  • Each thread interacts with each other in its own working memory. Improper memory control will cause data inconsistency

Thread creation method 1: inherit the thread class, override run(), and call start() to start the thread

Threads do not necessarily execute immediately, and the cpu schedules them

package testthread;

//Thread creation method 1: inherit the thread class, override run(), and call start() to start the thread
public class Thread1 extends Thread {

    @Override
    public void run() {
        //run method thread body
        for (int i = 0; i < 15; i++) {
            System.out.println("run Method body" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //The main thread is also called the main thread

        //Create thread object
        Thread1 thread1 = new Thread1();
        //Call start() to start the thread
        thread1.start();

        for (int i = 0; i < 20; i++) {
            System.out.println("main thread " + i);
            //Sleep for a while for easy observation
            Thread.sleep(50);
        }

        /** cpu The call is executed alternately in disorder, and the output result is different every time. The thread does not necessarily execute immediately, and the cpu arranges the scheduling
         main Thread 0
         run Method body 0
         run Method body 1
         run Method body 2
         run Method body 3
         run Method body 4
         run Method body 5
         run Method body 6
         run Method body 7
         run Method body 8
         run Method body 9
         run Method body 10
         run Method body 11
         run Method 12
         run Method body 13
         run Method body 14
         main Thread 1
         main Thread 2
         main Thread 3
         main Thread 4
         main Thread 5
         main Thread 6
         main Thread 7
         main Thread 8
         main Thread 9
         main Thread 10
         main Thread 11
         main Thread 12
         main Thread 13
         main Thread 14
         main Thread 15
         main Thread 16
         main Thread 17
         main Thread 18
         main Thread 19
         */
    }
}

html parses the image url and downloads it with multithreading that inherits the Thread class

Thread creation method 2: implement the Runnable interface and rewrite run(). The execution thread needs to be thrown to the Runnable interface implementation class (the thread class implements Runnable), and call start to start the thread

The advantage is that inheritance is a single inheritance, and there can be multiple implementations

package testthread;

//Thread creation method 2: implement the Runnable interface and rewrite run(). The execution thread needs to be thrown to the Runnable interface implementation class (the thread class implements Runnable), and call start to start the thread
public class Thread2 implements Runnable {

    @Override
    public void run() {
        //run method thread body
        for (int i = 0; i < 15; i++) {
            System.out.println("run Method body" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //The main thread is also called the main thread

        //Create a thread object and start the thread agent through the thread object
        Thread2 thread2 = new Thread2();
        Thread thread = new Thread(thread2);

        //Call start() to start the thread
        thread.start();

        for (int i = 0; i < 20; i++) {
            System.out.println("main thread " + i);
            //Sleep for a while for easy observation
            Thread.sleep(50);
        }

        /** cpu The calls are executed alternately out of order
         main Thread 0
         run Method body 0
         run Method body 1
         run Method body 2
         run Method body 3
         run Method body 4
         run Method body 5
         run Method body 6
         run Method body 7
         run Method body 8
         run Method body 9
         run Method body 10
         run Method body 11
         run Method body 12
         run Method body 13
         run Method body 14
         main Thread 1
         main Thread 2
         main Thread 3
         main Thread 4
         main Thread 5
         main Thread 6
         main Thread 7
         main Thread 8
         main Thread 9
         main Thread 10
         main Thread 11
         main Thread 12
         main Thread 13
         main Thread 14
         main Thread 15
         main Thread 16
         main Thread 17
         main Thread 18
         main Thread 19
         */
    }
}

Comparison between inheriting Thread and implementing Runable

Inherit Thread class
Start thread: subclass object start()
Not recommended: avoid the limitation of OOP single inheritance

Implement the Runable interface
Start Thread: pass in the target object + Thread object start()
Not recommended: avoid the limitation of OOP single inheritance and facilitate the use of the same object by multiple threads

Thread creation mode 3: implement the Callable interface with the return value

  1. To implement the Callable interface, the return value type is required
  2. When overriding the call method, you need to throw an exception
  3. Create target object
  4. Executors: create (execute) service newFixedThreadPool(1);
  5. Submit for execution: future result1 = Ser submit(t1);
  6. Get the result: Bollean R1 = result1 = result1 get();
  7. Shut down the service: Ser shutdownNow();
package testthread;

import org.apache.commons.io.FileUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.HtmlPage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//Multi thread synchronous downloading of pictures
public class DownloadCallableThread implements Callable<String> {

    private String url;//Network address
    private String fileName;//Save file name

    public DownloadCallableThread(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    //Thread executor: download pictures
    @Override
    public String call() {
        Downloader downloader = new Downloader();
        downloader.downloader(url, fileName);
        System.out.println("The download file name is" + fileName);
        return "The download file name is" + fileName + "===Download file time" + System.currentTimeMillis();
    }

    public static NodeList parser(String url) throws ParserException {

        /**Create parser object based on Url**/
        Parser parser = new Parser(url);

        /**The setting code must be the same as the Url code**/
        parser.setEncoding("utf-8");

        /** Build an Html page object**/
        HtmlPage htmlPage = new HtmlPage(parser);
        parser.visitAllNodesWith(htmlPage);

        /** Get all the nodes under the Body, which can be imagined as a tree like structure**/
        NodeList list = htmlPage.getBody();

        /** Create a Filter to Filter nodes, where nodes like "< img > < / img >" are obtained**/
        NodeFilter filter = new TagNameFilter("IMG");

        /** Get filtered nodes**/
        list = list.extractAllNodesThatMatch(filter, true);

        for (int c = 0; c < list.size(); c++) {
            ImageTag imageTag = (ImageTag) list.elementAt(c);
            /** Link Url of output picture**/
            System.out.println(imageTag.getImageURL());
        }
        return list;
    }

    public static void main(String[] args) throws ParserException, ExecutionException, InterruptedException {
        NodeList list = DownloadThread1.parser("http://2t6y.mydown.com/yuanqidesktop/tianji.html?softid=585&tid1=256&tid2=1001&tod1=17111");
        System.out.println(list.size());
        //Create execution service
        ExecutorService ser = Executors.newFixedThreadPool(list.size());

        DownloadCallableThread thread1 = new DownloadCallableThread(((ImageTag) list.elementAt(0)).getImageURL(), "1.png");
        DownloadCallableThread thread2 = new DownloadCallableThread(((ImageTag) list.elementAt(1)).getImageURL(), "2.png");
        DownloadCallableThread thread3 = new DownloadCallableThread(((ImageTag) list.elementAt(2)).getImageURL(), "3.png");
        DownloadCallableThread thread4 = new DownloadCallableThread(((ImageTag) list.elementAt(3)).getImageURL(), "4.png");
        DownloadCallableThread thread5 = new DownloadCallableThread(((ImageTag) list.elementAt(4)).getImageURL(), "5.png");
        DownloadCallableThread thread6 = new DownloadCallableThread(((ImageTag) list.elementAt(5)).getImageURL(), "6.png");
        DownloadCallableThread thread7 = new DownloadCallableThread(((ImageTag) list.elementAt(6)).getImageURL(), "7.png");
        DownloadCallableThread thread8 = new DownloadCallableThread(((ImageTag) list.elementAt(7)).getImageURL(), "8.png");
        DownloadCallableThread thread9 = new DownloadCallableThread(((ImageTag) list.elementAt(8)).getImageURL(), "9.png");
        DownloadCallableThread thread10 = new DownloadCallableThread(((ImageTag) list.elementAt(9)).getImageURL(), "10.png");
        DownloadCallableThread thread11 = new DownloadCallableThread(((ImageTag) list.elementAt(10)).getImageURL(), "11.png");
        //Submit for execution
        Future<String> r1 = ser.submit(thread1);
        Future<String> r2 = ser.submit(thread2);
        Future<String> r3 = ser.submit(thread3);
        Future<String> r4 = ser.submit(thread4);
        Future<String> r5 = ser.submit(thread5);
        Future<String> r6 = ser.submit(thread6);
        Future<String> r7 = ser.submit(thread7);
        Future<String> r8 = ser.submit(thread8);
        Future<String> r9 = ser.submit(thread9);
        Future<String> r10 = ser.submit(thread10);
        Future<String> r11 = ser.submit(thread11);

        //Get results
        String result1 = r1.get();
        String result2 = r2.get();
        String result3 = r3.get();
        String result4 = r4.get();
        String result5 = r5.get();
        String result6 = r6.get();
        String result7 = r7.get();
        String result8 = r8.get();
        String result9 = r9.get();
        String result10 = r10.get();
        String result11 = r11.get();
        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
        System.out.println(result5);
        System.out.println(result6);
        System.out.println(result7);
        System.out.println(result8);
        System.out.println(result9);
        System.out.println(result10);
        System.out.println(result11);

        //Shut down service
        ser.shutdownNow();

        /*
        "C:\Program Files\Java\jdk1.8.0_271\bin\java.exe" "-javaagent:D:\Users\Kingsoft\IntelliJ IDEA 2021.1.3\lib\idea_rt.jar=53686:D:\Users\Kingsoft\IntelliJ IDEA 2021.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_271\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_271\jre\lib\rt.jar;D:\workspace\Tests\target\classes;D:\Users\maven01_202112011747\apache-maven-3.8.4\.m2\commons-io\commons-io\2.11.0\commons-io-2.11.0.jar;D:\Users\maven01_202112011747\apache-maven-3.8.4\.m2\org\htmlparser\htmlparser\2.1\htmlparser-2.1.jar;D:\Users\maven01_202112011747\apache-maven-3.8.4\.m2\org\htmlparser\htmllexer\2.1\htmllexer-2.1.jar" testthread.DownloadCallableThread
https://dh1.cmcmcdn.com/sem/4/2/b/e/b/42bebba6bfd923aefede0b56d170013d.png
https://img-baofun.zhhainiao.com/market/semvideo/b8c4da367a3c730ca2c2e1eacf422107_preview.jpg
https://img-baofun.zhhainiao.com/market/238/F567AC46D63B85D2AA7E62AD01CD3692_preview.jpg
https://img-baofun.zhhainiao.com/market/238/b9c0ae90409426a9965e7247f9953658_preview.jpg
https://img-baofun.zhhainiao.com/market/238/c4302c9a3921d2f88b1322dc6173915d_preview.jpg
https://img-baofun.zhhainiao.com/market/238/9520e3c1f3b87509042affff4f446fe7_preview.jpg
https://img-baofun.zhhainiao.com/market/238/357E3204B3996B03966EE8116D229DF9_preview.jpg
https://img-baofun.zhhainiao.com/market/39/b25a301ef486487eb7992f1e81bd48d6_preview.jpg
https://img-baofun.zhhainiao.com/market/238/b9c0ae90409426a9965e7247f9953658_preview.jpg
https://img-baofun.zhhainiao.com/market/238/c4302c9a3921d2f88b1322dc6173915d_preview.jpg
https://img-baofun.zhhainiao.com/market/238/9520e3c1f3b87509042affff4f446fe7_preview.jpg
https://img-baofun.zhhainiao.com/market/238/357E3204B3996B03966EE8116D229DF9_preview.jpg
https://img-baofun.zhhainiao.com/market/39/b25a301ef486487eb7992f1e81bd48d6_preview.jpg
https://img-baofun.zhhainiao.com/market/semvideo/b8c4da367a3c730ca2c2e1eacf422107_preview.jpg
https://img-baofun.zhhainiao.com/market/238/F567AC46D63B85D2AA7E62AD01CD3692_preview.jpg
https://img-baofun.zhhainiao.com/market/238/F567AC46D63B85D2AA7E62AD01CD3692_preview.jpg
https://img-baofun.zhhainiao.com/market/238/b9c0ae90409426a9965e7247f9953658_preview.jpg
https://img-baofun.zhhainiao.com/market/238/c4302c9a3921d2f88b1322dc6173915d_preview.jpg
https://img-baofun.zhhainiao.com/market/238/9520e3c1f3b87509042affff4f446fe7_preview.jpg
https://img-baofun.zhhainiao.com/market/238/357E3204B3996B03966EE8116D229DF9_preview.jpg
https://img-baofun.zhhainiao.com/market/39/b25a301ef486487eb7992f1e81bd48d6_preview.jpg
https://img-baofun.zhhainiao.com/market/semvideo/b8c4da367a3c730ca2c2e1eacf422107_preview.jpg









31
 The download file name is 1 png
 The download file name is 5 png
 Download the file named 10 png
 Download the file named 8 png
 The download file name is 4 png
 Download the file named 7 png
 Download the file named 11 png
 The download file name is 6 png
 The download file name is 3 png
 The download file name is 2 png
 The download file name is 9 png
 The download file name is 1 Png = = = file download time 164426672406
 The download file name is 2 Png = = = file download time 164426674753
 The download file name is 3 Png = = = file download time 164426674467
 The download file name is 4 Png = = = download time 1644266734
 The download file name is 5 Png = = = download time 164426672985
 The download file name is 6 Png = = = file download time 164426674311
 Download the file named 7 Png = = = file download time 164426674035
 Download the file named 8 Png = = = download time 164426673623
 The download file name is 9 Png = = = file download time 164426674771
 Download the file named 10 Png = = = file download time 164426673090
 Download the file named 11 Png = = = file download time 164426674060

Process finished with exit code 0

         */
    }
}

//Downloader
class Downloader2 {
    //Download method
    public void downloader(String url, String fileName) {
        //Copy url address to file
        try {
            FileUtils.copyURLToFile(new URL(url), new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO Abnormal, Downloader Method exception");
        }
    }
}

Keywords: Java Multithreading

Added by dr4296 on Tue, 08 Feb 2022 01:40:37 +0200