preface

Multithreaded programming is one of the key factors to improve computing performance in the “multi-core era”, and it is also a core skill that developers must master. This article xiaobian takes you from six knowledge points to analyze JAVA multithreading, will be aimed at JAVA multithreading programming, the basic elaboration!

The main contents include:

Create Thread: implement Runnable interface (Thread priority 6, Thread lifecycle 7, sync code block

An overview,

1. Processes and threads

  • Process: A process is a running program.
  • Thread: A thread is a unit of execution within a process, the basic unit of CPU usage (scheduling) for a program. Responsible for the execution of programs in the current process. Is a single sequential control flow (execution path) in a process, and is a single execution path
  • After a program runs, there must be at least one process, and a process can contain multiple threads
  • In an operating system, processes are the basic unit of resource allocation and threads are the basic unit of scheduling.

Before threads, processes were the basic unit of both resource allocation and scheduling in the operating system

  • Single-threaded program: If there are more than one task can only be executed sequentially. When the execution of the previous task ends, the next task starts. The program has only one execution path
  • Multithreaded program: If more than one task can be executed at the same time. The program has multiple execution paths

Operating system development: Single-channel batch operation — > Multi-channel batch operating system — > time-sharing operating system (multi-process) — > Threaded batch operation: The program does not respond to user requests during execution. Can only run one program at a time, if you want to run any more programs in the computer, the multiple programs, only one order, if the running applications, in the process of operation, carried out some very time consuming IO operations (the process of transmitting data are not used to the CPU), as a result, the CPU is idle down, but the CPU is a computer, The most expensive multichannel batch operating system: Running multiple programs at the same time significantly improves CPU utilization, but once we have a program running, it is a time-sharing operating system that uses computer resources: Each process, with a fixed time slice, runs a fixed time slice, followed by the next process (switch)

  • Why are there threads? The cost of process switching is too high, so that each process switching, need to pay a small additional cost, in order to reduce the cost of process switching, the introduction of threads, improve CPU utilization

2. Thread scheduling

  • Time-sharing scheduling: All threads take turns using the CPU, evenly allocating the CPU time to each thread.
  • Preemptive scheduling: Priority is given to the threads with the highest priority using the CPU. If the threads have the same priority, one is randomly selected (thread randomness). Java uses preemptive scheduling
  • Reflects: the uncertainty of the program operation

1. CPU uses preemptive scheduling mode to switch between multiple threads at high speed. For a CPU core, only one thread can execute at a time, and the CPU switches between threads much faster than we might think, seemingly running at the same time. 2. Multi-threaded programs can not improve the running speed of the program, but can improve the running efficiency of the program, so that the CPU utilization rate is higher.

3. Thread control

  • Static void sleep(long millis) : To sleep the currently executing thread for the specified number of milliseconds.

    // Let the main Thread sleep for 3 seconds thread. sleep(3000); Timeunit.seconds.sleep (3); System.out.println(” wake up “);

  • Public final void join() :(makes the current thread) wait for the thread to terminate (the new thread terminates).

    SecondThread sec = new SecondThread(“zs”); SecondThread thr = new SecondThread(“lsii”); SecondThread fou = new SecondThread(“wangwu”);

    // Start the three thread objects sec.start(); // call the join method on the SEC thread and make the current thread (main) wait for the SEC thread to finish executing sec.join(); thr.start(); fou.start();

  • Public static void yield() : Suspends the currently executing thread object and executes another thread

The current thread is only told to give up CPU execution, but it is not prevented from continuing to rob CPU execution after giving up

  • Background thread (daemon thread) Public final void setDaemon(Boolean on) : Marks this thread as a daemon thread or a user thread. If all running threads are daemons, the Java VIRTUAL machine exits. This method must be called before starting the thread.

    SecondThread sec = new SecondThread(“zs”); SecondThread thr = new SecondThread(“lsii”); // Set the SEC and THR threads to sec.setdaemon (true); thr.setDaemon(true); / / start the SEC. Start (); thr.start(); // When SEC and THR are daemons, they interrupt

  • Public void interrupt() : Lets one thread control another thread (conditional: blocked). This method can be used to terminate another thread

1. If the thread is calling the wait(), wait(long), or wait(long, int) method of the Object class, Or the class’s join(), JOIN (long), JOIN (long, int), sleep(long), or sleep(long, int) blocking methods are blocking and it receives an InterruptedException 2. No action is required to interrupt an inactive thread. Interrupting a thread that is not blocking has no other effect

public class Test { public static void main(String[] args) { FiveThread fiveThread = new FiveThread(); fiveThread.start(); // In the main thread, fiveThread is terminated and fiveThread.interrupt() is dormant; }} // After sleeping for 5 seconds, Class FiveThread extends Thread{@override public void run() {try {// If a number of system resources are requested TimeUnit.SECONDS.sleep(5); System.out.println("FiveThread wakes up "); } catch (InterruptedException e) { e.printStackTrace(); / / exception meaning: even if I thread is abort, I also can guarantee the normal release resources}}} / / sell Java lang. InterruptedException: sleep interruptedCopy the code

4. The running principle of JAVA program

  • The Java command starts the JVM, that is, it starts a process that starts the main thread, which then calls the main method of a class, so the main methods run inside the main thread

  • When the JVM starts, there must be an execution path (thread) from main to the end of main. This thread is called the main thread in Java.

  • When the main thread of the program is executed, if a loop is encountered and the program stays in the specified position for too long, the following program cannot be executed immediately and needs to wait for the loop to end

  • The method runs in the thread in which it is called

  • The JVM is a multithreaded program, and each Java process is assigned one JVM instance

    Public class ThreadDemo {public static void main(String[] args) {public static void main(String[] args) { Int [] ints = new int[1024]; int[] ints = new int[1024]; ints = null; }}}

Second, the Thread class

1. An overview of the

  • A Thread is a Thread of execution in a program. The Java virtual machine allows applications to run multiple threads of execution concurrently
  • Not abstract class

2. Construction method

  • Thread() : Allocates a new Thread object
  • Thread(String name) : Allocates a new Thread object with the specified name as its Thread name

3. Common methods

  • Void start() : Causes the thread to start execution, and the Java VIRTUAL machine calls the thread’s run method
  • Void run() : the operation to be performed by the thread,
  • Static void sleep(Long millis) : Hibernates the currently executing thread for the specified millisecond
  • Static Thread currentThread() : Returns a reference to the Thread object currently executing thread.currentThread ()

4. Two ways to create a new thread of execution

  • Declare the class as a subclass of Thread. This subclass should override the Run method of Thread. Create an object and start a thread. The run method is equivalent to the main method of other threads.
  • Declare a class that implements the Runnable interface. The class then implements the run method. It then creates a Runnable subclass object that is passed into a thread constructor to start the thread.

Although there are two ways to implement the thread, in fact, objectively speaking, the thread itself only represents an independent execution path, the specific execution content is actually the Task itself, and the implementation of the execution path itself has no connection. It’s just that we developers want to run a task in a separate execution path (Thread object, i.e. a Thread)

Create Thread: inherit the Thread class

  • Steps to create a thread

  • Define a class that inherits Thread

  • Override the run method

  • Creating a subclass object is creating a thread object

  • Calling the start method starts the thread and lets it execute, while telling the JVM to call the run method

The thread object calls the run method without starting the thread. Only objects call methods. The thread object calls start to start the thread and has the JVM call the run method to execute in the opened thread

Public class Test {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) { ); Firstthread.run (); firstthread.run (); // Start a new thread mt.start(); / / start a thread, again will throw exceptions because IllegalThreadStateException / / a thread object can only be started once, / / if the same thread object, start times, it throws an exception. / / firstThread start (); // Create only one new object new MyThread(" second thread! ).start(); System.out.println(thread.currentThread ().getName()+" : main Thread!" ); }} class MyThread extends Thread {public MyThread(String name) {public MyThread(String name) { Specify the name of the thread super(name); Override public void run() {getName() system.out.println (getName() + ": running! ); }}Copy the code

Create thread: implement Runnable interface

1. Construction method of Runnable interface

  • Thread(Runnable target): Allocates a new Thread object so that target can be used as its run object
  • Thread(Runnable target,String name): Allocates a new Thread object to target as its run object; And uses the specified name as its name

2. Procedure for creating a thread

  • Define classes that implement the Runnable interface.
  • Override the run method in the interface
  • Create an object of the Thread class
  • Pass the Runnable interface subclass object as an argument to the Thread class constructor.
  • Call start() of Thread to start the Thread.

Constructor of Thread class:

  1. Thread(): Allocates a new Thread object
  2. Thread(String name): Assigns a new Thread object with the specified name as its Thread name
Public class Test {public static void main(String[] args) {MyRunnable MyRunnable = new MyRunnable(); Thread Thread = new Thread(myrunnable); // Start the thread thread.start(); for (int i = 0; i < 10; I++) {system.out.println ("main thread: executing!" +i); }}} class MyRunnable implements Runnable{MyRunnable implements Runnable; @override public void run() {for (int I = 0; i < 5; I++) {system.out.println (" my thread: executing!" +i); }}}Copy the code

3. Implement the principle of the Runnable interface

Why do we need a class to implement the Runnable interface? What’s the difference between inheriting the Thread class and implementing the Runnable interface? Only objects that create the Thread class can create threads. The Thread task is encapsulated in the Runnable interface’s run method, which is a subclass of the Runnable interface, so the subclass object is passed as an argument to the Thread constructor so that the Thread object can be created knowing which Thread’s task to run

4. Comparison of the two methods

  • Inheriting the Thread class

  • If a class already has a parent class, the Thread class cannot be inherited

  • Implement the Runnable interface mode

  • The limitation of single inheritance in mode 1 is solved

  • Another advantage is that it is easy for multiple threads to share data

The second way to implement the Runnable interface avoids the limitations of single inheritance and is therefore more commonly used. The Runnable interface is implemented in a more object-oriented manner. Threads are divided into two parts, one thread object and one thread task.

  • Inheriting the Thread class, Thread objects and Thread tasks are coupled together. Once you create a subclass of Thread, you create an object that is both a Thread object and a Thread task.
  • Implement the Runnable interface, separate the thread tasks into objects, the type is the Runnable interface type. The Runnable interface decouples thread objects from thread tasks

5. Thread priority

1. An overview of the

  • We can use the Thread class:

  • GetPriority method: gets the priority of the thread

  • SetPriority method: sets the priority of the thread

2. Range of thread priorities

  • If the thread priority range is set beyond the specified range, an exception will be thrown.

MAX_PRIORITY 10 // Maximum priority MIN_PRIORITY 1 // Minimum priority NORM_PRIORITY 5 // Default priority

/ / using thread1 setPriority (Thread. MAX_PRIORITY); / / set thread2. SetPriority (Thread. MIN_PRIORITY); System.out.println(thread1.getPriority()); / / to getCopy the code

3. Pay attention!

  • Priorities in the TThread class are not decisive for the JVM!

This means that when the JVM actually schedules threads, the priority it uses may not only include the static priority we set for each thread, but also take into account many other factors (the running state of each thread), so the priority we set is only a reference for the JVM

The life cycle of threads

1. Create a state

  • Creating a thread object

2. Ready

  • After the start ()
  • After you wake up
  • After the yield ()
  • Qualified to execute, waiting for CPU scheduling

3. Running status

  • Take execution authority and start execution

4. Blocked state

  • No executive qualification, no executive power

5. State of death

  • After execution, wait for garbage collection

7. Synchronize code blocks

1. Issues introduced — Thread safety issues

  • There are three conditions for thread-safety issues to occur:

1. Multi-thread running environment 2. Multi-thread access thread shared data (there is shared data) 3. Operations that access shared data are not atomic operations. Note: Atomic operation: an indivisible operation, equivalent to a one-time operation

  • When these three conditions are met at the same time, multi-threaded data security problems will occur
  • Solve the thread safety problem of multithreading: how to achieve exclusive access to shared resources by threads (you can only modify my access)?
  • useSynchronized code block

2. Synchronize code blocks

  • Synchronization code blocks implement thread synchronization
  • Thread synchronization: is to use the lock object, complete the multi-threaded running environment, the exclusive access to the shared resources (I go you can not go, you go I can not go)
  • Advantages: solve the security problem of multithreading
  • Disadvantages: resource consumption (when there are many threads, each thread running has to determine the synchronization lock, which is very expensive system resources)

Thread asynchrony: Threads run independently of each other (I go mine, you go yours).

  • Format:

    Synchronized (object) {// Critical section code for accessing shared resources}

1. Synchronization code block used in the object, called lock object — > lock role lock object, there is a flag bit: can represent two states, lock and unlock 2. The thread that holds the lock is the thread that holds the lock. When does the synchronization block lock the lock object? 4. When does the thread release the lock it holds? When executing a synchronized code block, the lock object of the synchronized code block will be released. 5. In the Java language, any object ** can act as a lock object (because any object has a flag bit indicating the lock, unlock state).

  • Note:

Although the lock object can be any object, all operations on the same (same multiple shared variables) must ensure that the same lock object is used within the synchronized code block to avoid thread-safety issues.

3. Synchronization method

  • When the scope of the synchronized code block extends to the entire method body, we can define the entire method as a synchronized method,Add synchronized to the method declaration
  • A common block of synchronized code:Synchronized {}
  • Synchronized methods:Void synchronized (){}
  • The lock object of the synchronization method isthis

Can static methods be defined as synchronous methods? A method that declares static synchronized, which uses the bytecode file object of the current class. Class

That’s the end of the article

Xiaobian here summarizes a multi-threaded concurrent programming mind map, want to understand the small partner can have a look

Like xiaobian to share technical articles can like attention oh!

Xiaobian here sorted out some Java core knowledge information collection

Public account: Kylin bug