Multithreading summary

What is multithreading: for example, if an account saves and stores at the same time, it is multithreading

There are four ways to create multithreading

1. Inherit Thread and re run the method

public class second {
    public static void main(String[] args) {
            check p1=new check();
            p1.setName("Secondary thread");
            p1.start();
            Thread.currentThread().setName("Main thread");
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+i);

        }
    }

}
class check extends Thread{
        int a=100;
    public void run(){
          for(int i=0;i<a;i++){
              System.out.println(getName()+a);
              a--;
          }
    }

Here I use two methods setName and getName. Their full names are

Thread.currentThread(). Why do I not use this in the check class and use this in main because check inherits thread

setName() sets the name of the current Thread, getName() outputs the name of the current Thread, and current Thread() returns the thread that is currently executing

It can be seen from the running results that the output of the main thread and the sub thread is uncertain and interactive, and they are all scrambling for cpu resources

If i want a or i to execute each other with a specific value, i can use   join() method

public class second {
    public static void main(String[] args) {
            check p1=new check();
            p1.setName("1 Secondary thread");
        p1.start();
            Thread.currentThread().setName("Main thread");
        for(int i=0;i<100;i++){
            if(i>20){
               try{
                   p1.join();
               }catch (Exception e){
                   e.printStackTrace();
               }
            }
            System.out.println(Thread.currentThread().getName()+i);

        }
    }

}
class check extends Thread{
        int a=70;
    public void run(){
          for(int i=a;i>0;i--){
//              if(i==50){
//                 try {
//                     Thread.currentThread().join();
//                 }catch (Exception E){
//                     E.printStackTrace();
//                 }
//              }
              System.out.println(getName()+i);

          }
    }


}

When the main thread and the sub thread seize the cpu execution right, the main thread i to 20 will execute the join method, and then the thread executing p1 will print the main thread after the p1 thread is executed. Note that p1.start() cannot be executed twice and can be called in the new object

You can see that I also used the join () method in the check class, but it was annotated by me. If I add this paragraph, the program will not terminate automatically and the side thread will only execute to   51 and the main thread will finish executing because the thread is locked and there is no termination condition

join () method: wait for the specified thread to terminate (my understanding of the method is to block the current thread and execute the caller thread). It will report an exception, so try it

2. Implement the Runnable interface and rewrite the run method:

public class Utility {
    public static void main(String[] args) {

        align a=new align();
        //Create a real column that implements the class
        Thread p1=new Thread(a,"1 Thread No");
        //Create the real column of Thread and set the Thread name
        Thread p2=new Thread(a,"2 Thread No");
        p1.start();
        //Start thread
        p2.start();
    }
}
class align implements Runnable{
    private int a=100;
    Object object=new Object();
    public void run(){
        while (true){
        synchronized (object){//Synchronization code
            if(a>0)
            {
                System.out.println( Thread.currentThread().getName()+a);
                a--;
//           
            }
        }}
    }
}

Print 1 to 100;

I called two start () methods, but I executed one 1 to 100 because there is only one align object. A is the data shared by the two of them. Synchronized (arbitrary object) {operation data} will reproduce the data if it is not written (there will be a security risk). The function of synchronized() is to lock. When the thread goes in, other threads cannot go in, Only after the thread is executed, can other prospects grab the cpu execution right and enter it. This class is also among them. (any object) is the monitor. The monitor is public. You can also use this. If it is used in inheritance, the object is static, and this class can also be used

There are also synchronization methods to solve security risks

public class ys implements Runnable{
    int a=100;
    public void run(){
        while (true){
            op();
        }
    }
    public synchronized void op(){
        try {
            Thread.sleep(10);
        }catch (Exception E){
            E.printStackTrace();
        }
        if(a>0)
            System.out.println(Thread.currentThread().getName()+a);
        a--;
    }
}
class d{
    public static void main(String[] args) {
        ys p1=new ys();
        Thread t1=new Thread(p1,"1 Thread No");
        Thread t2=new Thread(p1,"2 Thread No");
        t1.start();
        t2.start();
    }
}

The monitor here is this

also

public class dg implements Runnable{
    int a=100;
    ReentrantLock p1=new ReentrantLock();
    public void run(){
        while (true){
           p1.unlock();//Unlock
            try {
                System.out.println(Thread.currentThread().getName()+a);
                a--;
            }finally {
                p1.lock();
            }
        }
    }
}

This synchronization method is recommended to be flexible,

also

public class dh implements Runnable{
    int a=100;
    public void run(){
        while (true){
            synchronized (this){
                notify();
                if(a>0)
                System.out.println(Thread.currentThread().getName()+a);
            a-- ;
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }
    }
}

notify() unlock

wait() lock

Create in third

public class ed implements Callable {
    int a=0,sum=100;
    public Object call(){
        while (true){
            synchronized (this) {
                if (sum > 0) {
                    System.out.println(Thread.currentThread().getName() + sum);
                    a += sum;
                    sum--;
                } else {
                    return a;
                }
            }
        }
    }
}
public class da {
    public static void main(String[] args) {
        ed p1=new ed();
        FutureTask p=new FutureTask(p1);
        FutureTask po=new FutureTask(p1);
     Thread s1=  new Thread(po);
    Thread s2 =   new Thread(p);
    s2.setName("2" +"thread ");
        s1.setName("1" +"thread ");
        s1.start();s2.start();
        Object S;
        try{
            S = p.get();
            System.out.println("comprehensive"+S);
        }catch (Exception E){
            E.printStackTrace();
        }

    }
}
Implement the Call able interface to rewrite the call method. The real object FutureTask P = new FutureTask (P1) is required to start the thread class; Thread s1=    new Thread(po); You can use sl to start the thread, or you can not list thread, new Thread(po).start(); method. To receive the return value of call with FutureTask object. get()

Thread life cycle

Birth - > ready - > Run - > (blocking, return to ready state after blocking) - > death

thread priority

There are 1 and 5, 10. The default is 5


    

Keywords: Java Back-end

Added by SpasePeepole on Mon, 06 Dec 2021 05:35:10 +0200