java thread creation and lambda expression - java multithreading details 01

Posted by numan82 on Tue, 04 Jan 2022 09:29:37 +0100

1, Core thread concept

2, Three ways to create threads

Common method calls and multithreading

1. Inherit Thread class (key)
Method 1 of creating a Thread: inherit the Thread class, rewrite the run() method, and call start to start the Thread

Multithreading example 1

Multithreading can download multiple pictures at the same time

  • First, prepare a downloader, which can be downloaded online, then create a lib package, put the downloader into the package and convert it into library. Then write the downloader class.
  • Then write the thread class. Override the run method and create several threads in the main method.
    Step 1: write Downloader

    Step 2: write multithreading

    2. Implement Runnable interface (key)

    An example of thread implementation through runnable interface

    3. Comparison of the above two methods

4. Implement Callable interface (understand)

Examples and comparison


Benefits: you can submit return values and return exceptions
Note: when multiple threads operate on the same resource, the resource may be repeatedly occupied by threads.

3, Static proxy

1. Both real objects and proxy objects should implement the same interface
2. The proxy object should represent the real role
3. Benefits:
Proxy objects can do many things that real objects can't do
Real objects focus on doing their own things
Static proxy example
Just like when you get married, you have to ask the wedding company to act as your agent. (specific code not pasted)

4, Lamda expression

1. Definitions

2. Concept of functional interface
There is only one abstract function in an interface

3. Why use lambda expressions

  • Avoid too many anonymous inner class definitions
  • It can make your code look more concise
  • Removed a pile of useless code, leaving only the core logic
    4. Example of lambda expression
package com.oop;

/*
Derivation of lamda expression
 */
public class TestLamda {
    //3. Static internal class
    static class  Like2 implements ILike {
        @Override
        public void lambda() {
            System.out.println("i like lambda2");
        }
    }
    //Main function
    public static void main(String[] args) {
        ILike like = new Like();
        like.lambda();

        like = new Like2();
        like.lambda();
        //4. Local internal class
        class Like3 implements ILike{

            @Override
            public void lambda() {
                System.out.println("i like lambda3");
            }
        }
        like =new Like3();
        like.lambda();

        //5. Anonymous inner class: if there is no class name, you must use the interface or parent class
        like = new ILike() {
            @Override
            public void lambda() {
                System.out.println("i like lambda4");
            }
        };
        like.lambda();

        //6. Simplify with lambda
        like = ()->{
            System.out.println("i like lambda5");
        };
        like.lambda();
    }
}

//1. Define a functional interface
interface ILike{
    void lambda();
}

//2. Implementation class
class  Like implements ILike{
    @Override
    public void lambda() {
        System.out.println("i like lambda");
    }
}

5. Simplified example of lambda expression and use summary

package com.oop;

public class TestLambda2 {

    public static void main(String[] args) {
        Ilove love = new Love();
        love.love(2);

        Ilove love1 = (int a)->{
            System.out.println("i love you--->"+a);
        };
        love1.love(520);
        //Simplification 1: parameter type
        love = (a)->{
            System.out.println("i love you --->"+a);
        };
        //Simplify 2: simplify parentheses
        love = a->{
          System.out.println("i love you --->"+a);
        };
        love.love(521);

        //Simplification 3: remove curly braces
        love = a->System.out.println("i love you--->"+a);
        love.love(666);
        //Summary:
        /*
        1.lambda An expression can only be reduced to one line if there is only one line of code. If there are multiple lines, use code blocks
        2.The premise is that the interface is a functional interface: that is, there is only one abstract method in the interface
        3.You can also remove parameter types from multiple parameters. If you want to remove them, you must add parentheses, not just a little
        */
    }
}

//1. Define an interface
interface Ilove{
    void love(int a);
}
//2. Implement defined interfaces
class Love implements Ilove{
    @Override
    public void love(int a) {
        System.out.println("I love you ---->"+a);
    }
}

5, Thread state

6, Thread method

1. Thread stop

1. It is recommended that the thread be stopped normally - > utilization times, and dead loop is not recommended
2. It is recommended to use flag bit ----- > to set a flag bit
3. Do not use outdated methods such as stop or destroy or methods not recommended by JDK
4. Examples of thread stopping methods:

package com.oop;
/*
1.It is recommended that the thread stop normally -- > utilization times, and dead loop is not recommended
2.It is recommended to use flag bit ---- > to set a flag bit
3.Do not use outdated methods such as stop or destroy, or methods that are not recommended by JDK
 */
public class TestStop implements Runnable{

    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag)
        {
            System.out.println("run...Thread"+i++);
        }
    }

    //2. Set a public method to stop the thread and convert the flag bit
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop teststop = new TestStop();
        new Thread(teststop).start();

        for (int i = 0; i < 1000;i++){
            System.out.println("main");
            if (i==900)
            {
                //Call the stop method to switch the flag bit and stop the thread
                teststop.stop();
                System.out.println("The thread should stop");
            }
        }
    }
}

2. Thread hibernation

  • sleep time specifies the number of milliseconds the current thread is blocking
  • Exception InterruptedException in sleep
  • When the sleep time reaches, the thread enters the ready state
  • sleep can simulate network delay, countdown and so on
  • Each object has a lock, and sleep does not release the lock
  • Thread sleep example 1
package com.oop;

import jdk.nashorn.internal.ir.WhileNode;

public class TestSleep implements Runnable{

    //Number of votes
    private int ticketNums = 10;

    @Override
    public void run() {
                while (true){
                    if (ticketNums<=0)
                    {
                        break;
                    }else {
                        //Simulate the network delay, amplify the occurrence of the problem, and see the thread insecurity
                        try{
                            Thread.sleep(100);
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+"--->Got the second"+ticketNums--+"ticket");
                    }

                }
    }

    public static void main(String[] args) {
        TestSleep ticket = new TestSleep();

        new Thread(ticket,"Xiao Ming").start();
        new Thread(ticket,"indigo plant").start();
        new Thread(ticket,"Scalpers").start();
    }
}

  • Example 2 of thread sleep
package com.oop;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestSleep2 {

    public static void main(String[] args) {
        tenDown();
        //Print current system time
        Date startTime = new Date(System.currentTimeMillis());//Get current system time
        while (true)
        {
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //Analog countdown
    public static void tenDown(){
        int num = 10;
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(num--);
            if (num<=0){
                break;
            }
        }
    }
}

Topics: Java Back-end