day05 thread - October 21, 2021

Multithreading

1. What are the differences among programs, processes and threads?

Program: a piece of static code

Process: a running program that consumes memory

Thread: the internal execution path of a program. Multiple threads can operate the heap space in a process (there will be security risks for the shared resources that can be operated)

2. Creation and use of threads

(1) Thread creation

Mode 1:

/***
Mode 1:
  1,Create a Thread class to inherit Thread
  2,Override the run method in the Thread -- > declare the operation performed by this Thread in the run() method
  3,Create subclass object of thread
  4,Call the start() method through a subclass object
 */

public class ThreadTest{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        myThread.start();
    }
    
}
class MyThread extends Thread{
    @Override
    public void run(){
        //Specific operations in the thread --- for example: print an even number within 100
        for(int i = 0 ; i < 100 ; i++){
            if(i % 2 == 0){
                System.out.println(i);
            }       
        }
    }
}

Note: if you want to create multiple threads, you can call the start() method from new multiple threads

//How to create an anonymous subclass of Thread
new Thread(){
	@Override
	public void run(){}
}.start();

Mode 2:

/***
 1,Create a class to implement the Runnable interface
 2,The implementation class implements the abstract class method in Runnable, run()
 3,Create an implementation class object
 4,Instantiate this object and put it into the Thread constructor class
 5,The start() method is called through Thread
*/

class MyThread implements Thread{
    @Override
    public void run(){
        //Specific operations in the thread --- for example: print an even number within 100
        for(int i = 0 ; i < 100 ; i++){
            if(i % 2 == 0){
                System.out.println(i);
            }       
        }
    }
}

public class ThreadTest{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        Thread t1 = new Thread(myThread);
        t1.start(); 
    }
}

(2) Use of threads (common methods)

  • start(): start the current thread and call the run() method of the current thread

  • run(): you usually need to override the method in the Thread class and declare the operation to be performed by the created Thread in this method

  • currentThread(): a static method that returns the thread of the current method

  • getName(): get the name of the current thread

  • setName(): sets the name of the current thread

  • yield(): release the execution right of the current cpu, which means that thread 1 executed by the cpu will jump to another thread 2 after this method, but it may also be allocated to thread 1 after release

if(i%20 == 0){
    this.yield();  //this can be omitted to represent the current thread
}
  • join(): the join() method of calling thread B in thread A, when thread A enters the blocking state, the thread A ends the blocking state until the thread B is fully executed.

  • stop(): force the end of the thread (obsolete and unused)

  • Sleep (followed by the number of milliseconds): the number of milliseconds that allows the thread to sleep

  • isAlive(): judge whether the thread is still alive

3. Thread priority (10 gears)

(1) There are three constants:

public final static int MIN_PRIORITY =1;
public final static int NORM_PRIORITY =5;   //Default priority
public final static int MAX_PRIORITY =10;

(2) How to get and set the priority of the current thread

  • getPriority() gets the priority of the previous thread
//Thread.currentThread(). Can be omitted
Thread.currentThread().getPriority()
  • setPriority(int p) sets the priority of the previous thread
MyThread t1 = new MyThread();
t1.setPriority(10);   //Set the thread to the highest priority
//t1.setPriority(Thread.MAX_PRIORITY);   // You can also write that

4. What is the difference between inheritance and implementation?

It is recommended to create threads in the way of implementation,

(1) in java, classes are inherited in a single way, but the inheritance method must inherit Thread and cannot have its own parent class, so the implementation method is better

(2) when threads are created by inheritance, if multiple threads share a property, static needs to be added, and the implementation method points to the same property by default, so static does not need to be modified

5. Thread life cycle

JDK defines several states of threads with Thread.State class

  • New: when the object of a Thread class or its subclass is declared and created, the new Thread object is in the new state
  • Ready: after the newly created thread is started (), it will enter the thread queue and wait for the CPU time slice. At this time, it is ready to run, but it is not allocated CPU resources
  • Run: when the ready thread is scheduled to obtain CPU resources, it enters the running state. The run() method defines the operation and function of the thread
  • Blocking: in special cases, the execution is suspended or input operation is suspended artificially, and the blocking state is entered
  • Death: the thread completes all its work or is forced to end due to an exception

6. The difference between parallelism and concurrency

Parallel: multiple CPU s execute multiple tasks at the same time

Concurrency: one CPU executes multiple tasks at the same time

Under special circumstances, the execution is suspended or input operation is suspended artificially, and the blocking state is entered

  • Death: the thread completes all its work or is forced to end due to an exception

[external chain picture transferring... (img-XMKFuxEY-1634807062608)]

6. The difference between parallelism and concurrency

Parallel: multiple CPU s execute multiple tasks at the same time

Concurrency: one CPU executes multiple tasks at the same time

Keywords: Java

Added by rjs34 on Thu, 21 Oct 2021 11:11:30 +0300