Exception, thread, String

Keywords: Java

1: Abnormal

1. Concept

It is divided into error and Exception. Error is generally handled without writing code
Exception classification:
             Compile time exception (checked): IOException (FileNotFound), ClassNotFound (class not found)
            Run time exception (unchecked): null pointer, footmark out of bounds, wrong value type, ClassCast, etc

2. Exception handling                 

try catch :
          try the part where an exception may occur, and the part after the exception will not be executed;
          catch exception type object, you can use object. getMessage(), object. printStackTrace() to get exception information; If the exception type has a child parent relationship, the child class should be above and the parent class should be below
          finally, the part that must be executed is generally used for resource shutdown
Throws: if there is a child parent relationship, the exception of the child class throws < the exception of the parent class throws is required

3. Throw an exception manually

throw new exception type ("message")

2: Thread

1. Basic concepts

Unique to each thread: virtual machine stack, program counter
Threads share: common memory unit / memory address is the same - > allocate memory in the same heap - > access the same variables and objects

2.1. Thread creation method 1: inherit thread

Procedure: rewrite the run () method, create a class object and start the thread with the object. start(); Creating multiple threads requires new multiple objects
method:

public class pra01 {
    public static void main(String[] args) {
        //Thread creation mode 1:
        myThread myThread = new myThread();
        myThread.start();
        //The constructor sets the thread name
        finalstu.myThread special= new myThread("Special thread");
        //Main thread execution
        for (int i=0;i<100;i++){
            if (i%2 !=0)
            System.out.println(Thread.currentThread().getName()+i);
            if (i==20)
                try {
                    myThread.join();//The current thread is blocked. The myThread thread will not be released until the myThread thread is executed,
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }
}
class myThread extends Thread{
    @Override
    public void run() {
        for (int i=0;i<100;i++){
            if (i%2 == 0)
                try {
                    sleep(100);//You can only try catch because the run method of the parent class does not have throws sleep, which can only be used in the thread class
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            System.out.println(getName()+i);
            if (i%20 ==0)
                this.yield();//Release current execution rights
        }
    }
    public myThread(){
        super();
    }
    public myThread(String str){
        super();
        setName(str);
    }
}

2.2. Thread creation method 2: implement Runnable interface

Procedure: the implementation class rewrites the run () method; New implements the class object m, new Thread object T, and puts the implementation class object into the constructor; Call the t.start() method to start the thread;
            If the Runnable interface object in the Thread is not empty, call the run method of the interface, that is, the run method of the implementation class

3. Thread priority

getPriority(): returns the thread priority value
Setpriority (int newpriority): change thread priority
MAX_PRIORITY:10
NORM_ Priority: 5 (default priority)
MIN_PRIORITY:1
The subclass can inherit the priority of the parent class. The priority is only a probability problem, and the higher priority is not scheduled first

4. Thread life cycle

  5 thread synchronization

Sync code block:

Synchronized {code to be synchronized}
Synchronization monitor (lock). Any class object can be used as a lock, but the locks of multiple threads must be the same
                            Inherit Thread class: class name. Class
                            Implementation interface class: this, because multiple threads share one implementation class object

Synchronization method:

public synchronized void show() {/ / content to be synchronized}
      Synchronization monitor: this, so the static synchronized method should be written in the inheritance Thread mode to make the synchronization monitor become a class name. Class

Synchronous lock:

  Instantiate ReentrantLock in the implementation class: private ReentrantLock lock lock = new ReentrantLock();
  Try {lock. Lock(); / / call the lock method to get the synchronization monitor  
        Content to be synchronized}
  Finally {lock. Unlock(); / / call the unlock method  

6. Thread alternation

Written in the run method:
wait(); / / the current thread can enter the blocking state, which must be used in the synchronization code block or synchronization method
       //Release the synchronization monitor at the same time
       //wait() notify() notifyAll() are in the Object class
 notify(); / / wake up another blocked thread and get the synchronization monitor for the current thread. If multiple threads are blocked, wake up the thread with high priority
public class pra02 {
    public static void main(String[] args) {
        MThread mThread = new MThread();
        //The same object and three threads share the structure in mThread
        Thread t1 = new Thread(mThread);
        Thread t2 = new Thread(mThread);
        Thread t3 = new Thread(mThread);
        t1.start();//If the Runnable interface object in the Thread is not empty, call the run method of the interface, that is, the run method of the implementation class
        t2.start();
        t3.start();
    }
}
class MThread implements Runnable {
    private int i = 100;
    @Override
    public void run() {
        synchronized (this) {//If it inherits the thread class, the synchronization lock uses the class name. Class
            notify();//Wake up another blocked thread, and the current thread obtains the synchronization monitor; if multiple threads are blocked, wake up the thread with high priority
            for (; i > 0; i--) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
            try {
                wait();//It can make the current thread enter the blocking state, which must be used in the synchronization code block or synchronization method
                       //Release the synchronization monitor at the same time
                       //wait() notify() notifyAll() are in the Object class
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        show();
    }
    public synchronized void show() {//Synchronization monitor: this, so the static synchronized method should be written in the inherited Thread method,
        // The synchronization monitor becomes the class name. calss
        System.out.println("Synchronization method");
    }
}

7. Thread pool

 

 

Posted by irkevin on Thu, 04 Nov 2021 09:04:15 -0700