Java foundation-thread and concurrencyOne

Thread and concurrent Thread

basic concept

Program: A set of instructions that a computer can recognize and execute is a static code.

Process: a running activity of a program, a running program.

Thread: A component of a process, it represents a sequential flow of execution.


Process thread contact:

① Thread is the smallest execution and allocation unit of a process. It cannot move independently and must depend on the process. Numerous threads make up the process.

② Resources are allocated to the process, and all threads of the same process share all resources of the process.

image-20200412123650498

Process thread difference:

① Scheduling: Thread is the basic unit for scheduling and allocation, and Process is the basic unit for owning resources

② Concurrency: Not only can processes be executed concurrently, but multiple threads of the same process can also be executed concurrently

③ Owning resources: A process is an independent unit that owns resources. Threads do not own system resources, but can access resources belonging to processes

④ System overhead: When creating or canceling a process, because the system has to allocate and reclaim resources for it,

The overhead of the system is significantly greater than the overhead of creating or undoing threads, so using multithreading can reduce the resource overhead

The life cycle

image-20200412123305286

  • Freshman status:

    After creating a thread object using the new keyword and the Thread class or its subclasses, the thread object is in a new state. It remains in this state until the program starts () this thread.


  • Ready state:

    When the thread object calls the start () method, the thread enters the ready state. The thread in the ready state is in the ready queue, waiting to be scheduled by the thread scheduler in the JVM.


  • Operating status:

    If the thread in the ready state acquires CPU resources, it can execute run () and the thread is now in the running state. The thread in the running state is the most complex. It can become blocked, ready, and dead.


  • Blocking state:

    If a thread executes sleep, suspend, etc. methods, and loses the occupied resources, the thread enters the blocked state from the running state. You can re-enter the ready state after the sleep time has expired or after obtaining device resources. Can be divided into three types:

    • Waiting for blocking: The thread in the running state executes the wait () method to make the thread enter the waiting for blocking state.

    • Synchronization blocking: The thread fails to acquire the synchronized lock (because the lock is occupied by other threads).

    • Other blocking: When an I / O request is issued by calling the thread's sleep () or join (), the thread will enter the blocking state,

      When the sleep () state times out, join () waits for the thread to terminate or time out, or the I / O processing is complete, and the thread re-enters the ready state.


  • State of death:

    When a thread in a running state completes a task or other termination condition occurs, the thread switches to the termination state.

How to create threads

Inherit Thread class

1. Define a subclass that inherits Thread

2. Subclasses override Thread's run method

3. Instantiate subclass objects and create threads

4. Call the start method to start the thread


Source code

public class TestThread {
    public static void main(String[] args) {
        //创建线程方法1 继承Thread,重写run
        NewThread thread = new NewThread();
        thread.start();
        System.out.println("主线程开始打印数据");
        for (int i = 0; i < 5; i++) {
            System.out.println("主线程:"+i);
        }
    }
}

class NewThread extends Thread{
    @Override
    public void run() {
        System.out.println("分支线程开始打印数据");
        for (int i = 0; i < 5; i++) {
            System.out.println("分支线程:"+i);
        }
    }
}

Run the program a few times and find that the results obtained by the console are different. This is the randomness of CPU scheduling.

Implement the Runnable interface

1. Define a subclass that implements the Runnable interface

2. The subclass implements the run method of Runnable

3. Create a thread object through the Thread class constructor

4. Pass the Runnable instance as an argument to the constructor

5. Call the start method of the Thread instance to start the thread


Source code

public class TestThread {
    public static void main(String[] args) {
        //创建线程方法2 实现Runnable接口
        Thread thread = new Thread(new NewRunnable());
        thread.start();
        System.out.println("主线程开始打印数据");
        for (int i = 0; i < 5; i++) {
            System.out.println("主线程:"+i);
        }
    }
}

class NewRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("分支线程开始打印数据");
        for (int i = 0; i < 5; i++) {
            System.out.println("分支线程:"+i);
        }
    }
}

The difference between the two creation methods

  1. When creating multiple threads by implementing the Runnable interface, the thread class only implements the Runnable interface and can also inherit other classes. (recommend)
  2. Multiple threads can share the same Runnable implementation class object, which is conducive to resource synchronization.
  3. When creating multi-threads by inheriting the Thread class, if you need to access the current thread, use this directly to get the current thread.

Thread class

Construction method


image-20200412131959700


Common methods

method Functional description
public void start() This thread starts execution; the Java virtual machine calls the thread's run method.
public void run() If the thread is constructed using an independent Runnable run object, the run method of the Runnable object is called; otherwise, the method does nothing and returns.
public final void setName(String name) Change the thread name to be the same as the parameter name.
public final void setPriority(int priority) Change the priority of the thread.
public final void setDaemon(boolean on) Mark the thread as a daemon thread or user thread.
public final void join(long millisec) The maximum time to wait for this thread to terminate is millis milliseconds.
public void interrupt() Interrupt the thread. stop () is obsolete.
public final boolean isAlive() Test whether the thread is active.
public final synchronized void join(long millis) The maximum time to wait for this thread to terminate is millis milliseconds
public static void yield() Thread yields, suspends the currently executing thread object, and executes other threads.
public static void sleep(long millisec) Sleep the currently executing thread (suspend execution) within the specified number of milliseconds.
public static Thread currentThread() Returns a reference to the currently executing thread object.

priority

 /**  * The minimum priority that a thread can have.  */ 
public final static int MIN_PRIORITY = 1;

/**  * The default priority that is assigned to a thread.  */ 
public final static int NORM_PRIORITY = 5; 

/**  * The maximum priority that a thread can have.  */ 
public final static int MAX_PRIORITY = 10;

The range is 1-10. The higher the number, the higher the probability of system calls. The default priority is 5.


Example test code

public class FunctionTest {
    public static void main(String[] args) throws InterruptedException {
        Thread threadChild = new NewThread();
        Thread threadRun = new Thread(new NewRunnable(),"线程2  ");
		//先设置优先级
        threadChild.setPriority(1);
        threadRun.setPriority(10);
		//启动线程
        threadChild.start();
        threadRun.start();
		//获取线程属性
        threadChild.setName("线程1  ");
        System.out.println(threadChild.getName());
        System.out.println(threadRun.getName());
        System.out.println(Thread.currentThread().getName());

        if (threadChild.isAlive())
            System.out.println(threadChild.getName()+"活着");

        System.out.println("------有人在中间插队------");
        threadChild.join();//执行完毕才到下一行
        System.out.println("------有人在中间插队------");
		//打印线程状态
        threadRun.interrupt();
        System.out.println(threadChild.isAlive());
        System.out.println(threadRun.isAlive());

    }
}

postscript

The above is just a very basic conceptual understanding.

Many problems will be encountered in practical applications, such as:

  • Thread synchronization
  • Inter-thread communication
  • Thread deadlock
  • Thread control: suspend, stop and resume

Guess you like

Origin www.cnblogs.com/1101-/p/12684973.html