current position:Home>Detailed explanation of multithreading lesson 2: thread implementation (key points, learn quickly)

Detailed explanation of multithreading lesson 2: thread implementation (key points, learn quickly)

2021-08-21 10:10:35 Stay up late and knock the code every day

    //run Method thread body 

    for(int i = 0; i < 20 ; i++){

        System.out.println(" I'm looking at the code ---"+i);

    }



}

public static void main(String[] args) {

    //main Threads , The main thread 



    // Create a thread object 

    TestThread1 testThread1 = new TestThread1();



    // call start() Method to open the thread , perform run Method 

    testThread1.start();

    for(int i = 0; i < 20; i++){

        System.out.println(" I'm learning multithreading ---"+i);

    }

}

}




** Execution results **  

![ Insert picture description here ](https://s2.51cto.com/images/20210820/1629392736786280.jpg)  

** Main thread and run Method threads execute alternately .**



### [](https://gitee.com/vip204888/java-p7)3、 Case study : Download the pictures 



** Code **




     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

package com.kaung.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;

import java.io.IOException;

import java.net.URL;

// practice Thread , Realize multi thread synchronous download picture

public class TestThread2 extends Thread{

private String url; // Network picture address 

private String name; // Saved file name 

public TestThread2(String url,String name){

    this.url=url;

    this.name=name;

}

// Download Image thread executor 

@Override

public void run() {

    WebDownloader webDownloader = new WebDownloader();

    webDownloader.downloader(url,name);

    System.out.println(" Downloaded the file named :"+name);

}



public static void main(String[] args) {

    TestThread2 t1 = new TestThread2("https://public-cdn-oss.mosoteach.cn/books/mobile/[email protected]","1.jpg");

    TestThread2 t2 = new TestThread2("https://public-cdn-oss.mosoteach.cn/books/mobile/[email protected]","2.jpg");

    TestThread2 t3 = new TestThread2("https://public-cdn-oss.mosoteach.cn/books/mobile/[email protected]","3.jpg");

    // To download t1

    t1.start();

    // then t1

    t2.start();

    // Last t3

    t3.start();

}

}

// Downloader

class WebDownloader{

// Download method 

public void downloader(String url,String name){

    try {

        FileUtils.copyURLToFile(new URL(url),new File(name));

    } catch (IOException e) {

        e.printStackTrace();

        System.out.println("IO abnormal ,downloader Method exception ");

    }

}

}




** Run a screenshot **



![ Insert picture description here ](https://s2.51cto.com/images/20210820/1629392737129605.jpg)  

 We started three threads , These three threads do not execute in order , Who snatched the time first , Who will execute first .



 The conclusion is verified :** In a process , If multiple threads are opened up , The running of the thread is scheduled by the scheduler , The scheduler is closely related to the operating system , The order of intervention cannot be considered .**



### [](https://gitee.com/vip204888/java-p7)4、 Realization Runnable Interface 



** step **



1.  ** Definition MyRunnable Class implementation Runnable Interface **

    

2.  ** Realization run() Method , Write thread executor **

    

3.  ** Creating thread objects , call start() Method to start the thread **

    



** Code **




     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.

package com.kaung.demo01;

public class TestThread3 implements Runnable{

@Override

public void  run(){

    //run Method thread body 

    for(int i = 0; i < 20 ; i++){

        System.out.println(" I'm looking at the code ---"+i);

    }



}

public static void main(String[] args) {



    // establish runable Implementation class object of interface 

    TestThread3 testThread3 = new TestThread3();

    // Creating thread objects , Open our thread through thread object , agent 

    Thread thread = new Thread(testThread3);

    thread.start();



    for(int i = 0; i < 200; i++){

        System.out.println(" I'm learning multithreading ---"+i);

    }

}

}




** Recommended Runnable object , because Java Limitations of single inheritance **



### [](https://gitee.com/vip204888/java-p7)5、 Summary 



** Inherit Thread class **



*   ** A subclass inherits Thread Class has multithreading capabilities **

*   ** Start thread : Subclass object . start()**

*    Not recommended : avoid OOP Limitations of single inheritance 



** Realization Runable Interface **



*   ** Implementation interface Runnable Multithreading capability **

*   ** Start thread : Incoming target object +Thread object .start()**

*    Recommended : Avoid the limitations of single inheritance , Flexible and convenient , It is convenient for the same object to be used by multiple threads 



### [](https://gitee.com/vip204888/java-p7)6、 Initial concurrency problem 



** Code **




     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.

package com.kaung.demo01;

// Multiple threads operate on an object at the same time

// An example of buying a train ticket

// Find the problem : When multiple threads operate on the same resource , Thread unsafe , Data disorder .

public class TestThread4 implements Runnable {

private int ticketNums = 10;

@Override

public void run() {

    while(true){

        if((ticketNums<=0)){

            break;

        }

        // Analog delay 

        try {

            Thread.sleep(200);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println(Thread.currentThread().getName()+"---> Got the number "+ticketNums-- +" ticket ");

    }

}



public static void main(String[] args) {

    TestThread4 ticket = new TestThread4();



    new Thread(ticket," Xiao Ming ").start();

    new Thread(ticket," teacher ").start();

    new Thread(ticket," Scalpers ").start();

}

}




** Run a screenshot **  

![ Insert picture description here ](https://s2.51cto.com/images/20210820/1629392739933656.jpg)  

** Find the problem  :  When multiple threads operate on the same resource , Thread unsafe , Data disorder .**



### [](https://gitee.com/vip204888/java-p7)7、 Tortoise and the hare 



![ Insert picture description here ](https://s2.51cto.com/images/20210820/1629392741433321.jpg)  

** Code emulation **




     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

package com.kaung.demo01;

// A race between the hare and the tortoise

public class Race implements Runnable{

private static String winner;

@Override

public void run() {

    for (int i = 0; i <= 100; i++) {



        // Simulated rabbit rest 

        if(Thread.currentThread().getName().equals(" The rabbit ")&&i%10==0) {

            try {

                Thread.sleep(10);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        // Judge whether the game is over 

        boolean flag = gameOver(i);

        if(flag){

            break;

        }

        System.out.println(Thread.currentThread().getName()+"---> ran "+i+" Step ");

    }

}

// Judge whether to finish the game 

private boolean gameOver(int steps){

    // Judge whether there is a winner 

    if(winner!=null) // There are already Winners 

    {

        return true;

    }

    if(steps>=100){

        winner = Thread.currentThread().getName();

        System.out.println("winner is "+winner);

        return true;

    }

    return false;

}



public static void main(String[] args) {

    Race race = new Race();

    new Thread(race," The rabbit ").start();

    new Thread(race," Tortoise ").start();

}

}




### [](https://gitee.com/vip204888/java-p7)8、 Realization Callable Interface ( Understanding can )



![ Insert picture description here ](https://s2.51cto.com/images/20210820/1629392743252290.jpg)



### [](https://gitee.com/vip204888/java-p7)9、 Static proxy 



![ Insert picture description here ](https://s2.51cto.com/images/20210820/1629392744765239.jpg)  

** Pattern summary **



*    Real objects and proxy objects should implement the same interface 

*    Proxy object to proxy real object 



** benefits **



*    Proxy objects can do a lot of things that real objects can't 

*    Real objects focus on doing their own things 



** Code **




     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

import sun.plugin2.main.client.WDonatePrivilege;

// Summary of static proxy mode

// Real objects and proxy objects should implement the same interface

// Proxy object to proxy real object

// benefits

// Proxy objects can do a lot of things that real objects can't 

// Real objects focus on doing their own things 

public class StaticProxy {

public static void main(String[] args) {

    You you = new You();



    new Thread(()-> System.out.println(" I love you! ")).start();



    new WeddingCompany(new You()).HappyMarry();



}

}

interface Marry{

void HappyMarry();

}

// Real role , You're going to get married

class You implements Marry {

@Override

public void HappyMarry() {

    System.out.println(" I'm getting married , Super happy ");

}

}

// Proxy object , Help you get married

class WeddingCompany implements Marry {

// Who is acting for -->  The real target character 

private Marry target; // Target audience 



public WeddingCompany(Marry target) {

    this.target = target;

}



@Override

public void HappyMarry() {

    brfore();

    this.target.HappyMarry(); // This is the real object 

    after();

General catalogue display

There are eight nodes in this note ( from the shallower to the deeper ), It is divided into three modules .

High performance . Seckill involves a lot of concurrent reads and writes , So it's critical to support high concurrency access . The note will be from the dynamic and static separation scheme of design data 、 Discovery and isolation of hot spots 、 Peak clipping and layered filtering of requests 、 The ultimate optimization of the server side 4 Focus on .

Uniformity . The realization of commodity inventory reduction in second kill is also key . As one can imagine , A limited number of items are requested many times at the same time to reduce inventory , Inventory reduction is divided into “ Take stock reduction ”“ Payment minus stock ” And withholding , In the process of large concurrent update, the accuracy of data should be guaranteed , It's hard to imagine . therefore , A node will be used to explain how to design the second kill inventory reduction scheme .

High availability . Although it introduces many extreme optimization ideas , But in reality, there are always some situations we can't consider , Therefore, it is necessary to ensure the high availability and correctness of the system , And design a PlanB Come to the bottom , So that you can still deal with the worst case . At the end of the note , It will take you to think about which links you can design the bottom plan .


Limited space , It is impossible to show a module in detail ( These points are collected in this 《 High concurrency spike top tutorial 》 in ), Code friends who feel in need , Please forward it ( It can help more people to see !)  Click here , You can get free downloads !!

Due to too much content , Only part of the content is intercepted here . Need this 《 High concurrency spike top tutorial 》 Little buddy , Would you please give me some praise, share and support ( It can help more people to see !)

copyright notice
author[Stay up late and knock the code every day],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210821101030334G.html

Random recommended