java learning [1]_multithreading

Keywords: Java

Multithreading

Briefly introduce the knowledge of multithreading in java

  • (1) Multithread introduction:
    With the CPU entering the era of dual-core and multi-core, the advantages of multi-threading are becoming more and more obvious. Multithreading is a concurrent mechanism in Java, which means that multiple operations can be performed simultaneously at the same time.
    Here is an example of multi-threading, multi-threading practical development example: in many websites, when the user registers, the system will inform the user that the registration has been successful on the one hand, on the other hand, it will send mail to the user in the Email filled in at the time of registration.

  • (2) How to define threads:
    There are two ways to define threads, one is to inherit the Thread class, the other is to implement the Runnable interface.
    A. Inheriting Thread classes: Defining a thread can be achieved by inheriting Thread classes, which is a relatively simple way to define threads. There is a run method in the Thread class that needs to be overridden in the defined thread.
    B. Implementing Runnable Interface: Implementing Runnable Interface. There is an abstract run method in the Runnable interface. When implementing the Runnable interface, it is necessary to implement the run method.
    Both methods need to define a run method, whether it is by overriding the parent method or by implementing the interface method. Run method is the entry of a thread, which must be possessed by a thread. Using threads defined by implementing the Runnable interface, it is not easy to create threaded objects. Because class objects are created directly, it is not a thread object that is created. To create thread objects, you must use the Thread class:
    XianCheng x = new XianCheng(); Thread t = new Thread(x);

  • (3) Threads have a life cycle:
    The lifecycle of threads is divided into five different states: new state, ready state, running state, waiting/blocking state and dead state.
    1. New: When a thread object is created;
    2. Prepare: After the thread in the new state is called the start method;
    3. Running: Once the thread in the ready state is selected by the system, the thread will enter the running state if it gains CPU time.
    4. Wait/Block: Many thread scheduling methods, including sleep, blocking, hanging, and waiting, will be explained in later scheduling chapters. Using these methods, all running threads are scheduled to wait/block state.
    5. Death: When the run method in the thread is finished or the program terminates abnormally, the thread will enter a dead state.

  • (5) Common functions:
    1. sleep(long millis): Sleep the currently executing thread within a specified number of milliseconds (pause execution)
    2. join(): Waiting for the termination of the t thread. How to use it. Join is a method of the Thread class, which is called directly after starting a thread. That is to say, join() has the function of "waiting for the thread to terminate". What we need to understand here is that the thread refers to the main thread waiting for the termination of the sub-thread. That is, the code after the join() method is called by the sub-thread, which can only be executed when the sub-thread ends.
    3. yield(): Suspend the thread object currently being executed and execute other threads.

Code 1: Inherit the Thread method and use the sleep function:

package TestDuoxiancheng;
//Use sleep(long millis): Sleep the currently executing thread (pause execution) for a specified number of milliseconds
public class TestThread1 extends Thread{
    private String name;
    private int count = 5;
    public TestThread1(String name){
        this.name = name;
    }
    public void run() {
        for(int i=0;i<5;i++){
            System.out.println(name + "Threads are running, at this point  count= " + count--);
            try {
                sleep((int) Math.random() * 5);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread1 T1 = new TestThread1("A");
        TestThread1 T2 = new TestThread1("B");
        System.out.println("Realization Thread Class method:");
        T1.start();
        T2.start();
        }
}

Code 2: Implement the Runnable interface:

package TestDuoxiancheng;
//Use sleep(long millis): Sleep the currently executing thread (pause execution) for a specified number of milliseconds
public class TestRunnable1 implements Runnable{
     private int count=4;
     public void run(){
        for(int i=0;i<5;i++){
              System.out.println(Thread.currentThread().getName() + "Threads are running  count= " + count--);
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestRunnable1 TR1 = new TestRunnable1();
        Thread T1 = new Thread(TR1,"C");
        Thread T2 = new Thread(TR1,"D");
        System.out.println("inherit Runnable Method:");
        T1.start();
        T2.start();
    }
}

Posted by macdumbpling on Fri, 22 Mar 2019 12:54:52 -0700