JAVA multithreading notes

JAVA multithreading

Thread creation

1.Thread class

  1. The custom Thread class inherits the Thread class

  2. Rewrite the run() method to write the thread execution body

  3. Create a thread object and call the start() method to start the thread

//Thread creation method 1: inherit the thread class, rewrite the run() method, and call start to start the thread
public class TestThread1 extends Thread{
    @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);
        }
    }
    //main thread
    public static void main(String[] args) {
        
        //Create a thread object
        TestThread1 testThread1 = new TestThread1();
        //Call the start() method to start the thread (alternate execution)
        testThread1.start();
        //Call the run() method, execute run() first, and then execute the main method
        //testThread1.run();
        for (int i = 0; i < 20; i++) {
            System.out.println("I'm multithreading"+i);
        }
​
    }
}
​
/*be careful! Thread startup is not necessarily executed immediately, but is scheduled by the CPU*/

2. Recommendation of Runnable interface (implementation of Runnable interface)

  1. Define the MyRunnable class to implement the Runnable interface

  2. Implement the run() method and write the thread execution body

  3. Create a thread object and call the start() method to start the thread

//Thread creation mode 2: implement the runnable interface and rewrite the run method. The execution thread needs to throw in the runnable class interface implementation class and call the start method
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) {
        //Create an implementation class object for the runnable interface
        TestThread3 testThread3 = new TestThread3();
        //Create a thread object and start our thread through the thread object
        Thread thread = new Thread(testThread3);
​
        thread.start();
​
        //Short for newthread (testthread3) start();
​
        for (int i = 0; i < 20; i++) {
            System.out.println("I'm multithreading"+i);
        }
​
    }
}

3.Callable interface (implement callable interface)

  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. Create execution service

ExecutorService ser = Executors.newFixedThreadPool(1);
  1. Submit for execution

Future<Boolean>result1 = ser.submit(t1);
  1. Get results

boolean r1 = result.get()
  1. Shut down service

ser.shutdownNow();

/*Implementation of callable method for picture download case*/
​
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
​
/**
 * TODO
 *
 * @author wlj
 * @version 1.0
 * @Description
 * @date 2022/1/15 16:39
 */
​
/*
callable Benefits of
 Exceptions can be thrown
 With return value
 */
​
//Thread creation mode 3: implement the callable interface
public class TestCallable implements Callable<Boolean> {
    private String url;//Network picture address
    private String name;//Saved file name
​
    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }
​
​
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("Downloaded file named:" + name);
        return true;
    }
​
    public static void main(String[] args) throws ExecutionException, InterruptedException {
​
​
        TestCallable testThread1 = new TestCallable("https://webstatic.mihoyo.com/upload/puzzle/2021/12/22/1a4f9ac397162af7b11616ea7acb5115_4472408160447119381.png", "1.jpg");
        TestCallable testThread2 = new TestCallable("https://webstatic.mihoyo.com/upload/puzzle/2021/12/22/1a4f9ac397162af7b11616ea7acb5115_4472408160447119381.png", "2.jpg");
        TestCallable testThread3 = new TestCallable("https://webstatic.mihoyo.com/upload/puzzle/2021/12/22/1a4f9ac397162af7b11616ea7acb5115_4472408160447119381.png", "3.jpg");
​
/*======================================================================*/
        //Create execution service thread pool
        ExecutorService ser = Executors.newFixedThreadPool(3);
​
        //Submit for execution
        Future<Boolean> r1 = ser.submit(testThread1);
        Future<Boolean> r2 = ser.submit(testThread2);
        Future<Boolean> r3 = ser.submit(testThread3);
​
        //Get results
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();
​
        //Print return results
        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
​
        //Shut down service
        ser.shutdownNow();
/*====================================================================*/ 
    }
}
​
​
//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 There is a problem with the method");
        }
    }
}

Thread sleep

  1. sleep specifies the number of milliseconds the current thread is blocking

  2. Exception InterruptedException in sleep

  3. When the sleep time reaches, the thread enters the ready state

  4. sleep can simulate network delay and countdown

  5. Each object has a lock, and sleep does not release the lock

//Analog countdown
public class TestSleep2 {
    public static void main(String[] args) {
//        try {
//            tenDown();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
​
        //Print current 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));
                startTime = new Date(System.currentTimeMillis());//Update current time
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
​
    public static void tenDown() throws InterruptedException{
        int num = 10;
        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if(num<=0){
                break;
            }
        }
    }
}

Thread shutdown

  1. It is not recommended to use the stop(), destroy() method provided by JDK [obsolete]

  2. It is recommended that the thread stop itself

  3. It is recommended to use a flag bit to terminate the variable. When flag = false, the thread will be terminated

//Test stop
    //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 shoot a flag bit
    //3. Do not use outdated methods such as stop or destroy or methods not recommended by JDK
public class TestStop implements Runnable{

    //1. Set an identification bit
    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"+i);
            if(i == 900){
                //Call the stop method written by yourself to switch the flag bit and stop the thread
                testStop.stop();
            }
        }
    }
}

Thread comity

  1. Comity thread, which suspends the currently executing thread without blocking

  2. Transition a thread from a running state to a ready state

  3. If the CPU is rescheduled, comity may not be successful

//Test comity thread
    //Comity does not necessarily succeed. It depends on your mood
public class TestYield {

    public static void main(String[] args) {
        MyYield myYield = new MyYield();

        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }

}

class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"Thread starts execution");
        Thread.yield();//Comity
        System.out.println(Thread.currentThread().getName()+"Thread stop execution");
    }
}

Thread enforcement

//Test the Join method and imagine jumping in line
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("vip Here comes the thread"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException{
        
        //Start our thread
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();
        
        //Main thread

        for (int i = 0; i < 500; i++) {
            if(i == 200){
                thread.join();//Jump in line
            }
            System.out.println("main"+i);
        }
    }
}

Thread state observation

public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("///");
        });


        //Observation state
        Thread.State state = thread.getState();
        System.out.println(state); //NEW

        //Observe after startup
        thread.start();//Start thread
        state = thread.getState();
        System.out.println(state);//Run

        while(state != Thread.State.TERMINATED){//As long as the thread does not terminate, it always outputs the state
            Thread.sleep(100);
            state = thread.getState();//Update thread status
            System.out.println(state);//Print thread status
        }
    }
}

thread priority

The priority of threads is expressed in numbers, ranging from 1 to 10

  1. Thread.MIN_PRIORITY = 1;

  2. Thread.MAX_PRIORITY = 10;

  3. Thread.NORM_PRIORITY = 5;

Change or get priority in the following ways

  1. getPriority()

  2. setPriority(int xxx)

public class TestPriority {
​
    public static void main(String[] args) {
        //Default priority of main thread
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
​
        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);
​
        //Set priority first and start
        t1.start();
        t2.setPriority(1);
        t2.start();
        t3.setPriority(4);
        t3.start();
        t4.setPriority(Thread.MAX_PRIORITY);
        t4.start();
​
    }
}
​
class MyPriority implements Runnable{
​
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

Daemon thread

  1. Threads are divided into user threads and daemon threads

  2. The virtual machine must ensure that the user thread has completed execution

  3. The virtual machine does not have to wait for the daemon thread to finish executing

  4. For example, record the operation log in the background, monitor the memory, and wait for garbage collection

//Test daemon thread
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();
​
        Thread thread = new Thread(god);
        thread.setDaemon(true);//The default is false, which means that it is a user thread. Normal threads are user threads
        thread.start();//God daemon thread start
​
        new Thread(you).start();//Your user thread starts
​
    }
}
​
//lord
​
class God implements  Runnable{
    @Override
    public void run() {
        while(true){
            System.out.println("God bless you");
        }
    }
}
​
//you
class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("You live happily all your life");
        }
        System.out.println("-====goodbye! world!====-");
    }
}
​

Keywords: Java Multithreading

Added by afterburner on Wed, 19 Jan 2022 01:45:18 +0200