JAVA multithreading Foundation: basic syntax

  • Threads run faster than processes

Three schemes to realize multithreading

Can implement Thread class

  • In any case, as long as multithreading is defined, there will always be only one scheme for multithreading startup. The start() method in the Thread class

  • strat0() is called internally, which is a JNI implementation method. The JVM implements different start0() methods according to different systems

    import java.util.function.*;
    class MyThread extends Thread{
    	private String title;
    	public MyThread(String title){
    		this.title = title;
    	}
    	@Override
    	public void run(){
    		for(int i= 0;i< 10;i++){
    			System.out.println(this.title + "i = " + i);
    		}
    	}
    }
    public class JavaDemo{
        public static void main(String[] arges){
            MyThread myThread01 = new MyThread("TEST01 ");
    		myThread01.start();
            MyThread myThread02 = new MyThread("TEST02 ");
    		myThread02.start();
            MyThread myThread03 = new MyThread("TEST03 ");
    		myThread03.start();
        }
    }
    

    Runnable to realize multithreading

  • After 1.8, it becomes a functional interface, which can directly implement lambda functional interface

  • The Runnable implementation is the first consideration in the development, and Thread.start() method

  • With the help of construction method: public Thread(Runnable target) implementation

    • This is the implementation interface, so MyThread can be used as a normal class to inherit other classes or implement multiple interfaces
import java.util.function.*;
class MyThread implements Runnable{
	private String title;
	public MyThread(String title){
		this.title = title;
	}
	@Override
	public void run(){
		for(int i= 0;i< 10;i++){
			System.out.println(this.title + "i = " + i);
		}
	}
}
public class JavaDemo{
    public static void main(String[] arges){
        Thread thread = new Thread(new MyThread("TEST"));
		thread.start();
    }
}
  • Lambda function formula (super concise)

    public class JavaDemo{
        public static void main(String[] arges){
    		Runnable run = ()->{
    			System.out.println("Execute in multithreading here");
    		};
            new Thread(run).start();
        }
    }
    
#Simpler
import java.util.function.*;
public class JavaDemo{
    public static void main(String[] arges){
        new Thread(()->{
			System.out.println("dsfsdf");
		}).start();
    }
}
The relationship between Thread and Runnable
  • ````Public class thread extensions object implements Runnable {} ` ` thread class is also a subclass that implements the Runnable interface
  • As we have learned above, multithreaded methods are mainly implemented by Thread, so resource calls of operating system are also called by Thread
  • Thread is the proxy class, MyThread or the class that implements the Runnable interface is the real class
  • The essence of multithreaded development is that multiple threads can preempt unified resources

Callable implementation of multithreading

  • The disadvantage of Runnable is that it cannot give the main thread a return value after execution

  • New method after 1.5 java.util.concurrent.Callable interface, using generics to return data

  • Method flow chart

Runnable and Callable
  • Runnable is a multithreaded implementation interface proposed in JDK 1.0, while Callable is proposed after JDK 1.5

  • java.lang.Runnable There is only one run() method proposed in the interface, and no return value

  • java.util.concurrent The. Callable interface provides a call() method, which can have a return value;

    import java.util.concurrent.Callable;
    import java.util.concurrent.FutureTask;
    
    class MyThread implements Callable<String>{
    	@Override
    	public String call() throws Exception{
    		for(int i=0;i < 1000;i++){
    			System.out.println("==========" + i);
    		}
    		return "=====end========";
    	}
    }
    public class JavaDemo{
        public static void main(String[] arges)throws Exception{
            FutureTask<String> task = new FutureTask<>(new MyThread());
    		new Thread(task).start();
    		System.out.println(task.get());
        }
    }
    

Other small knowledge

Multithreaded state

state
  • establish
  • start()
    • Ready state
      • Blocking state
    • running state
  • termination
Process and sleep
  • Several JVMs can be started in a program, and each JVM is a process
  • Sleep can be set to the accuracy of milliseconds and nanoseconds. If it is interrupted, an Exception of the Exception subclass will be thrown, which must be handled
  • When all threads run the same method, there will also be a sequence, not an absolute execution together

The name of the thread

  • In order to get some thread operations, you can get them by the name of the thread

    • Construction method: public Thread(Runnable target,String name)
    • Setting Name: public final void setName(String name)
    • Name retrieved: public final String getName();
    • How to get the current thread: Thread.currentThread().getName()

Thread interrupt

  • Judge whether it is interrupted: public boolean isInterrupted(); / / if it is interrupted, return true
  • Interrupt thread execution: public void interrupt();

Thread enforcement

public class test {

    public static void main(String[] args) {
       Thread mainThread = Thread.currentThread();
       Thread thread = new Thread(()->{
           for (int x = 0; x < 100; x++){
               if (x == 3){
                   try {
                       mainThread.join();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
               System.out.println("thread == " + x);
           }
       });
        thread.start();
        for (int i = 0; i < 100; i++){
            System.out.println("Hegemonic main thread mainThread == " + i);
        }
    }
}

Thread comity

  • Courtesy: public void yield()

  • Every time there is a competition, there will be comity once, most of the time, but it is not obvious

      public static void main(String[] args) {
           Thread thread = new Thread(()->{
               for (int x = 0; x < 100; x++){
                   if (x % 3 == 0){
                       Thread.yield();
                       System.out.println("===========I'll do it once===========");
                   }
                   try {
                       Thread.sleep(100);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   System.out.println("thread == " + x);
               }
           });
            thread.start();
            for (int x = 0; x < 100; x++){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Hegemonic main thread mainThread == " + x);
            }
        }
    

Priority Setting

  • Set priority: public final void setPriority(int new Priority);
    • Default priority: 5(NORM_PRIORITY)
    • Highest priority: MAX_PRIORITY 10
    • Medium priority: NORM_PRIORITY 5
    • Minimum priority: MIN_PRIORITY 1
  • Get priority: public final int getPriority()

Synchronization method

Synchronization code block, synchronization method

  • Synchronize code blocks, slow down

Waiting mechanism of thread

  • Wait: wait()
  • Set the wait time (long timeout, int nanos)
  • Wake up the first waiting thread: notify()
  • Wake all threads: notifyALL()
  • Disabled methods: stop(), suspend(), destroy()
  • Using global variables to stop threads

Daemons

-Set the daemons: public final void setDaemon(boolean on);
-Judge whether it is a guardian thread: public final boolean isDaemon();
-When it is set as a daemonic thread, the daemonic thread will also end when the whole program ends
 -The biggest Guardian thread of JVM is GC thread. The program ends and GC ends together

volatile

Normal variable processing steps:
  • Get the original data content copy of the variable
  • Mathematical calculation with copy as variable
  • Save the calculated variables to the original space
volatile keyword
  • It means that you do not use the replica, but directly operate the variable, so it is not a synchronous operation, and you need to synchronize the keyword
The difference between volatile and synchronized
  • Volail is mainly used on attributes, while synchronized is used on code blocks and methods
  • volatile can't describe the process of synchronization, it's just a process of direct memory, avoiding the operation of replica, and synchronized is to achieve synchronization
  • volatile distribution synchronized handles synchronization and can run faster

StringBuffer

  • Thread safe string addition method, provided after 1.0

  • Append: new StringBuffer(“ www.cn ”). insert(4, "mldn") is appended at the beginning of the fourth

  • Partial deletion: buf.append(“ www.mldn.com ”).delete(4,8).insert(4,“bridge”);//“ www.bridge.com "

  • Payment reversal: buf.reverse()

  • StringBuilder: non thread safety is more efficient, which is provided after 1.5

Tags: Java jvm Lambda JDK

Posted on Sun, 21 Jun 2020 06:16:11 -0400 by Aaron_Escobar